diff --git a/google/cloud/bigtable/data/_async/client.py b/google/cloud/bigtable/data/_async/client.py index 5c9649c41..4d52c64c2 100644 --- a/google/cloud/bigtable/data/_async/client.py +++ b/google/cloud/bigtable/data/_async/client.py @@ -87,6 +87,7 @@ else: from typing import Iterable # noqa: F401 from grpc import insecure_channel + from grpc import intercept_channel from google.cloud.bigtable_v2.services.bigtable.transports import BigtableGrpcTransport as TransportType # type: ignore from google.cloud.bigtable.data._sync_autogen.mutations_batcher import _MB_SIZE @@ -366,11 +367,21 @@ async def _manage_channel( break start_timestamp = time.monotonic() # prepare new channel for use + # TODO: refactor to avoid using internal references: https://github.com/googleapis/python-bigtable/issues/1094 old_channel = self.transport.grpc_channel new_channel = self.transport.create_channel() + if CrossSync.is_async: + new_channel._unary_unary_interceptors.append( + self.transport._interceptor + ) + else: + new_channel = intercept_channel( + new_channel, self.transport._interceptor + ) await self._ping_and_warm_instances(channel=new_channel) # cycle channel out of use, with long grace window before closure self.transport._grpc_channel = new_channel + self.transport._logged_channel = new_channel # invalidate caches self.transport._stubs = {} self.transport._prep_wrapped_messages(self.client_info) diff --git a/google/cloud/bigtable/data/_sync_autogen/client.py b/google/cloud/bigtable/data/_sync_autogen/client.py index b89e23207..7b1e72ad6 100644 --- a/google/cloud/bigtable/data/_sync_autogen/client.py +++ b/google/cloud/bigtable/data/_sync_autogen/client.py @@ -66,6 +66,7 @@ from google.cloud.bigtable.data._cross_sync import CrossSync from typing import Iterable from grpc import insecure_channel +from grpc import intercept_channel from google.cloud.bigtable_v2.services.bigtable.transports import ( BigtableGrpcTransport as TransportType, ) @@ -282,8 +283,10 @@ def _manage_channel( start_timestamp = time.monotonic() old_channel = self.transport.grpc_channel new_channel = self.transport.create_channel() + new_channel = intercept_channel(new_channel, self.transport._interceptor) self._ping_and_warm_instances(channel=new_channel) self.transport._grpc_channel = new_channel + self.transport._logged_channel = new_channel self.transport._stubs = {} self.transport._prep_wrapped_messages(self.client_info) if grace_period: diff --git a/google/cloud/bigtable_admin/__init__.py b/google/cloud/bigtable_admin/__init__.py index 2884a96ab..319c1f332 100644 --- a/google/cloud/bigtable_admin/__init__.py +++ b/google/cloud/bigtable_admin/__init__.py @@ -46,6 +46,18 @@ from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( CreateInstanceRequest, ) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + CreateLogicalViewMetadata, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + CreateLogicalViewRequest, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + CreateMaterializedViewMetadata, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + CreateMaterializedViewRequest, +) from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( DeleteAppProfileRequest, ) @@ -55,6 +67,12 @@ from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( DeleteInstanceRequest, ) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + DeleteLogicalViewRequest, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + DeleteMaterializedViewRequest, +) from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( GetAppProfileRequest, ) @@ -64,6 +82,12 @@ from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( GetInstanceRequest, ) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + GetLogicalViewRequest, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + GetMaterializedViewRequest, +) from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( ListAppProfilesRequest, ) @@ -88,6 +112,18 @@ from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( ListInstancesResponse, ) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + ListLogicalViewsRequest, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + ListLogicalViewsResponse, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + ListMaterializedViewsRequest, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + ListMaterializedViewsResponse, +) from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( PartialUpdateClusterMetadata, ) @@ -109,6 +145,18 @@ from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( UpdateInstanceMetadata, ) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + UpdateLogicalViewMetadata, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + UpdateLogicalViewRequest, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + UpdateMaterializedViewMetadata, +) +from google.cloud.bigtable_admin_v2.types.bigtable_instance_admin import ( + UpdateMaterializedViewRequest, +) from google.cloud.bigtable_admin_v2.types.bigtable_table_admin import ( CheckConsistencyRequest, ) @@ -230,6 +278,8 @@ from google.cloud.bigtable_admin_v2.types.instance import Cluster from google.cloud.bigtable_admin_v2.types.instance import HotTablet from google.cloud.bigtable_admin_v2.types.instance import Instance +from google.cloud.bigtable_admin_v2.types.instance import LogicalView +from google.cloud.bigtable_admin_v2.types.instance import MaterializedView from google.cloud.bigtable_admin_v2.types.table import AuthorizedView from google.cloud.bigtable_admin_v2.types.table import Backup from google.cloud.bigtable_admin_v2.types.table import BackupInfo @@ -253,12 +303,20 @@ "CreateClusterRequest", "CreateInstanceMetadata", "CreateInstanceRequest", + "CreateLogicalViewMetadata", + "CreateLogicalViewRequest", + "CreateMaterializedViewMetadata", + "CreateMaterializedViewRequest", "DeleteAppProfileRequest", "DeleteClusterRequest", "DeleteInstanceRequest", + "DeleteLogicalViewRequest", + "DeleteMaterializedViewRequest", "GetAppProfileRequest", "GetClusterRequest", "GetInstanceRequest", + "GetLogicalViewRequest", + "GetMaterializedViewRequest", "ListAppProfilesRequest", "ListAppProfilesResponse", "ListClustersRequest", @@ -267,6 +325,10 @@ "ListHotTabletsResponse", "ListInstancesRequest", "ListInstancesResponse", + "ListLogicalViewsRequest", + "ListLogicalViewsResponse", + "ListMaterializedViewsRequest", + "ListMaterializedViewsResponse", "PartialUpdateClusterMetadata", "PartialUpdateClusterRequest", "PartialUpdateInstanceRequest", @@ -274,6 +336,10 @@ "UpdateAppProfileRequest", "UpdateClusterMetadata", "UpdateInstanceMetadata", + "UpdateLogicalViewMetadata", + "UpdateLogicalViewRequest", + "UpdateMaterializedViewMetadata", + "UpdateMaterializedViewRequest", "CheckConsistencyRequest", "CheckConsistencyResponse", "CopyBackupMetadata", @@ -327,6 +393,8 @@ "Cluster", "HotTablet", "Instance", + "LogicalView", + "MaterializedView", "AuthorizedView", "Backup", "BackupInfo", diff --git a/google/cloud/bigtable_admin_v2/__init__.py b/google/cloud/bigtable_admin_v2/__init__.py index f2aea1667..1d2d13cf0 100644 --- a/google/cloud/bigtable_admin_v2/__init__.py +++ b/google/cloud/bigtable_admin_v2/__init__.py @@ -28,12 +28,20 @@ from .types.bigtable_instance_admin import CreateClusterRequest from .types.bigtable_instance_admin import CreateInstanceMetadata from .types.bigtable_instance_admin import CreateInstanceRequest +from .types.bigtable_instance_admin import CreateLogicalViewMetadata +from .types.bigtable_instance_admin import CreateLogicalViewRequest +from .types.bigtable_instance_admin import CreateMaterializedViewMetadata +from .types.bigtable_instance_admin import CreateMaterializedViewRequest from .types.bigtable_instance_admin import DeleteAppProfileRequest from .types.bigtable_instance_admin import DeleteClusterRequest from .types.bigtable_instance_admin import DeleteInstanceRequest +from .types.bigtable_instance_admin import DeleteLogicalViewRequest +from .types.bigtable_instance_admin import DeleteMaterializedViewRequest from .types.bigtable_instance_admin import GetAppProfileRequest from .types.bigtable_instance_admin import GetClusterRequest from .types.bigtable_instance_admin import GetInstanceRequest +from .types.bigtable_instance_admin import GetLogicalViewRequest +from .types.bigtable_instance_admin import GetMaterializedViewRequest from .types.bigtable_instance_admin import ListAppProfilesRequest from .types.bigtable_instance_admin import ListAppProfilesResponse from .types.bigtable_instance_admin import ListClustersRequest @@ -42,6 +50,10 @@ from .types.bigtable_instance_admin import ListHotTabletsResponse from .types.bigtable_instance_admin import ListInstancesRequest from .types.bigtable_instance_admin import ListInstancesResponse +from .types.bigtable_instance_admin import ListLogicalViewsRequest +from .types.bigtable_instance_admin import ListLogicalViewsResponse +from .types.bigtable_instance_admin import ListMaterializedViewsRequest +from .types.bigtable_instance_admin import ListMaterializedViewsResponse from .types.bigtable_instance_admin import PartialUpdateClusterMetadata from .types.bigtable_instance_admin import PartialUpdateClusterRequest from .types.bigtable_instance_admin import PartialUpdateInstanceRequest @@ -49,6 +61,10 @@ from .types.bigtable_instance_admin import UpdateAppProfileRequest from .types.bigtable_instance_admin import UpdateClusterMetadata from .types.bigtable_instance_admin import UpdateInstanceMetadata +from .types.bigtable_instance_admin import UpdateLogicalViewMetadata +from .types.bigtable_instance_admin import UpdateLogicalViewRequest +from .types.bigtable_instance_admin import UpdateMaterializedViewMetadata +from .types.bigtable_instance_admin import UpdateMaterializedViewRequest from .types.bigtable_table_admin import CheckConsistencyRequest from .types.bigtable_table_admin import CheckConsistencyResponse from .types.bigtable_table_admin import CopyBackupMetadata @@ -102,6 +118,8 @@ from .types.instance import Cluster from .types.instance import HotTablet from .types.instance import Instance +from .types.instance import LogicalView +from .types.instance import MaterializedView from .types.table import AuthorizedView from .types.table import Backup from .types.table import BackupInfo @@ -142,6 +160,10 @@ "CreateClusterRequest", "CreateInstanceMetadata", "CreateInstanceRequest", + "CreateLogicalViewMetadata", + "CreateLogicalViewRequest", + "CreateMaterializedViewMetadata", + "CreateMaterializedViewRequest", "CreateTableFromSnapshotMetadata", "CreateTableFromSnapshotRequest", "CreateTableRequest", @@ -151,6 +173,8 @@ "DeleteBackupRequest", "DeleteClusterRequest", "DeleteInstanceRequest", + "DeleteLogicalViewRequest", + "DeleteMaterializedViewRequest", "DeleteSnapshotRequest", "DeleteTableRequest", "DropRowRangeRequest", @@ -163,6 +187,8 @@ "GetBackupRequest", "GetClusterRequest", "GetInstanceRequest", + "GetLogicalViewRequest", + "GetMaterializedViewRequest", "GetSnapshotRequest", "GetTableRequest", "HotTablet", @@ -179,10 +205,16 @@ "ListHotTabletsResponse", "ListInstancesRequest", "ListInstancesResponse", + "ListLogicalViewsRequest", + "ListLogicalViewsResponse", + "ListMaterializedViewsRequest", + "ListMaterializedViewsResponse", "ListSnapshotsRequest", "ListSnapshotsResponse", "ListTablesRequest", "ListTablesResponse", + "LogicalView", + "MaterializedView", "ModifyColumnFamiliesRequest", "OperationProgress", "OptimizeRestoredTableMetadata", @@ -209,6 +241,10 @@ "UpdateBackupRequest", "UpdateClusterMetadata", "UpdateInstanceMetadata", + "UpdateLogicalViewMetadata", + "UpdateLogicalViewRequest", + "UpdateMaterializedViewMetadata", + "UpdateMaterializedViewRequest", "UpdateTableMetadata", "UpdateTableRequest", ) diff --git a/google/cloud/bigtable_admin_v2/gapic_metadata.json b/google/cloud/bigtable_admin_v2/gapic_metadata.json index 7cd09c43b..c56fde6e7 100644 --- a/google/cloud/bigtable_admin_v2/gapic_metadata.json +++ b/google/cloud/bigtable_admin_v2/gapic_metadata.json @@ -25,6 +25,16 @@ "create_instance" ] }, + "CreateLogicalView": { + "methods": [ + "create_logical_view" + ] + }, + "CreateMaterializedView": { + "methods": [ + "create_materialized_view" + ] + }, "DeleteAppProfile": { "methods": [ "delete_app_profile" @@ -40,6 +50,16 @@ "delete_instance" ] }, + "DeleteLogicalView": { + "methods": [ + "delete_logical_view" + ] + }, + "DeleteMaterializedView": { + "methods": [ + "delete_materialized_view" + ] + }, "GetAppProfile": { "methods": [ "get_app_profile" @@ -60,6 +80,16 @@ "get_instance" ] }, + "GetLogicalView": { + "methods": [ + "get_logical_view" + ] + }, + "GetMaterializedView": { + "methods": [ + "get_materialized_view" + ] + }, "ListAppProfiles": { "methods": [ "list_app_profiles" @@ -80,6 +110,16 @@ "list_instances" ] }, + "ListLogicalViews": { + "methods": [ + "list_logical_views" + ] + }, + "ListMaterializedViews": { + "methods": [ + "list_materialized_views" + ] + }, "PartialUpdateCluster": { "methods": [ "partial_update_cluster" @@ -114,6 +154,16 @@ "methods": [ "update_instance" ] + }, + "UpdateLogicalView": { + "methods": [ + "update_logical_view" + ] + }, + "UpdateMaterializedView": { + "methods": [ + "update_materialized_view" + ] } } }, @@ -135,6 +185,16 @@ "create_instance" ] }, + "CreateLogicalView": { + "methods": [ + "create_logical_view" + ] + }, + "CreateMaterializedView": { + "methods": [ + "create_materialized_view" + ] + }, "DeleteAppProfile": { "methods": [ "delete_app_profile" @@ -150,6 +210,16 @@ "delete_instance" ] }, + "DeleteLogicalView": { + "methods": [ + "delete_logical_view" + ] + }, + "DeleteMaterializedView": { + "methods": [ + "delete_materialized_view" + ] + }, "GetAppProfile": { "methods": [ "get_app_profile" @@ -170,6 +240,16 @@ "get_instance" ] }, + "GetLogicalView": { + "methods": [ + "get_logical_view" + ] + }, + "GetMaterializedView": { + "methods": [ + "get_materialized_view" + ] + }, "ListAppProfiles": { "methods": [ "list_app_profiles" @@ -190,6 +270,16 @@ "list_instances" ] }, + "ListLogicalViews": { + "methods": [ + "list_logical_views" + ] + }, + "ListMaterializedViews": { + "methods": [ + "list_materialized_views" + ] + }, "PartialUpdateCluster": { "methods": [ "partial_update_cluster" @@ -224,6 +314,16 @@ "methods": [ "update_instance" ] + }, + "UpdateLogicalView": { + "methods": [ + "update_logical_view" + ] + }, + "UpdateMaterializedView": { + "methods": [ + "update_materialized_view" + ] } } }, @@ -245,6 +345,16 @@ "create_instance" ] }, + "CreateLogicalView": { + "methods": [ + "create_logical_view" + ] + }, + "CreateMaterializedView": { + "methods": [ + "create_materialized_view" + ] + }, "DeleteAppProfile": { "methods": [ "delete_app_profile" @@ -260,6 +370,16 @@ "delete_instance" ] }, + "DeleteLogicalView": { + "methods": [ + "delete_logical_view" + ] + }, + "DeleteMaterializedView": { + "methods": [ + "delete_materialized_view" + ] + }, "GetAppProfile": { "methods": [ "get_app_profile" @@ -280,6 +400,16 @@ "get_instance" ] }, + "GetLogicalView": { + "methods": [ + "get_logical_view" + ] + }, + "GetMaterializedView": { + "methods": [ + "get_materialized_view" + ] + }, "ListAppProfiles": { "methods": [ "list_app_profiles" @@ -300,6 +430,16 @@ "list_instances" ] }, + "ListLogicalViews": { + "methods": [ + "list_logical_views" + ] + }, + "ListMaterializedViews": { + "methods": [ + "list_materialized_views" + ] + }, "PartialUpdateCluster": { "methods": [ "partial_update_cluster" @@ -334,6 +474,16 @@ "methods": [ "update_instance" ] + }, + "UpdateLogicalView": { + "methods": [ + "update_logical_view" + ] + }, + "UpdateMaterializedView": { + "methods": [ + "update_materialized_view" + ] } } } diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/async_client.py b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/async_client.py index b6e77aaea..ad3745c06 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/async_client.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/async_client.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import logging as std_logging from collections import OrderedDict import re from typing import ( @@ -58,6 +59,15 @@ from .transports.grpc_asyncio import BigtableInstanceAdminGrpcAsyncIOTransport from .client import BigtableInstanceAdminClient +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + class BigtableInstanceAdminAsyncClient: """Service for creating, configuring, and deleting Cloud @@ -91,6 +101,16 @@ class BigtableInstanceAdminAsyncClient: ) instance_path = staticmethod(BigtableInstanceAdminClient.instance_path) parse_instance_path = staticmethod(BigtableInstanceAdminClient.parse_instance_path) + logical_view_path = staticmethod(BigtableInstanceAdminClient.logical_view_path) + parse_logical_view_path = staticmethod( + BigtableInstanceAdminClient.parse_logical_view_path + ) + materialized_view_path = staticmethod( + BigtableInstanceAdminClient.materialized_view_path + ) + parse_materialized_view_path = staticmethod( + BigtableInstanceAdminClient.parse_materialized_view_path + ) table_path = staticmethod(BigtableInstanceAdminClient.table_path) parse_table_path = staticmethod(BigtableInstanceAdminClient.parse_table_path) common_billing_account_path = staticmethod( @@ -289,6 +309,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.bigtable.admin_v2.BigtableInstanceAdminAsyncClient`.", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "credentialsType": None, + }, + ) + async def create_instance( self, request: Optional[ @@ -301,7 +343,7 @@ async def create_instance( clusters: Optional[MutableMapping[str, gba_instance.Cluster]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Create an instance within a project. @@ -344,7 +386,6 @@ async def create_instance( ``mycluster`` rather than ``projects/myproject/instances/myinstance/clusters/mycluster``. Fields marked ``OutputOnly`` must be left blank. - Currently, at most four clusters can be specified. This corresponds to the ``clusters`` field on the ``request`` instance; if ``request`` is provided, this @@ -352,8 +393,10 @@ async def create_instance( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -369,7 +412,10 @@ async def create_instance( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, instance_id, instance, clusters]) + flattened_params = [parent, instance_id, instance, clusters] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -436,7 +482,7 @@ async def get_instance( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.Instance: r"""Gets information about an instance. @@ -455,8 +501,10 @@ async def get_instance( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Instance: @@ -470,7 +518,10 @@ async def get_instance( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -522,7 +573,7 @@ async def list_instances( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_instance_admin.ListInstancesResponse: r"""Lists information about instances in a project. @@ -541,8 +592,10 @@ async def list_instances( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.ListInstancesResponse: @@ -553,7 +606,10 @@ async def list_instances( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -602,7 +658,7 @@ async def update_instance( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.Instance: r"""Updates an instance within a project. This method updates only the display name and type for an Instance. @@ -620,8 +676,10 @@ async def update_instance( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Instance: @@ -674,7 +732,7 @@ async def partial_update_instance( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Partially updates an instance within a project. This method can modify all fields of an Instance and is the @@ -702,8 +760,10 @@ async def partial_update_instance( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -719,7 +779,10 @@ async def partial_update_instance( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([instance, update_mask]) + flattened_params = [instance, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -785,7 +848,7 @@ async def delete_instance( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Delete an instance from a project. @@ -804,13 +867,18 @@ async def delete_instance( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -861,7 +929,7 @@ async def create_cluster( cluster: Optional[instance.Cluster] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Creates a cluster within an instance. @@ -902,8 +970,10 @@ async def create_cluster( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -918,7 +988,10 @@ async def create_cluster( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, cluster_id, cluster]) + flattened_params = [parent, cluster_id, cluster] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -982,7 +1055,7 @@ async def get_cluster( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.Cluster: r"""Gets information about a cluster. @@ -1001,8 +1074,10 @@ async def get_cluster( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Cluster: @@ -1015,7 +1090,10 @@ async def get_cluster( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1067,7 +1145,7 @@ async def list_clusters( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_instance_admin.ListClustersResponse: r"""Lists information about clusters in an instance. @@ -1088,8 +1166,10 @@ async def list_clusters( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.ListClustersResponse: @@ -1100,7 +1180,10 @@ async def list_clusters( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1149,7 +1232,7 @@ async def update_cluster( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Updates a cluster within an instance. @@ -1166,8 +1249,10 @@ async def update_cluster( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -1229,7 +1314,7 @@ async def partial_update_cluster( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Partially updates a cluster within a project. This method is the preferred way to update a Cluster. @@ -1267,8 +1352,10 @@ async def partial_update_cluster( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -1283,7 +1370,10 @@ async def partial_update_cluster( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([cluster, update_mask]) + flattened_params = [cluster, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1347,7 +1437,7 @@ async def delete_cluster( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a cluster from an instance. @@ -1366,13 +1456,18 @@ async def delete_cluster( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1423,7 +1518,7 @@ async def create_app_profile( app_profile: Optional[instance.AppProfile] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.AppProfile: r"""Creates an app profile within an instance. @@ -1458,8 +1553,10 @@ async def create_app_profile( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.AppProfile: @@ -1471,7 +1568,10 @@ async def create_app_profile( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, app_profile_id, app_profile]) + flattened_params = [parent, app_profile_id, app_profile] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1527,7 +1627,7 @@ async def get_app_profile( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.AppProfile: r"""Gets information about an app profile. @@ -1546,8 +1646,10 @@ async def get_app_profile( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.AppProfile: @@ -1559,7 +1661,10 @@ async def get_app_profile( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1611,7 +1716,7 @@ async def list_app_profiles( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAppProfilesAsyncPager: r"""Lists information about app profiles in an instance. @@ -1633,8 +1738,10 @@ async def list_app_profiles( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListAppProfilesAsyncPager: @@ -1648,7 +1755,10 @@ async def list_app_profiles( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1712,7 +1822,7 @@ async def update_app_profile( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Updates an app profile within an instance. @@ -1738,8 +1848,10 @@ async def update_app_profile( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -1752,7 +1864,10 @@ async def update_app_profile( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([app_profile, update_mask]) + flattened_params = [app_profile, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1814,9 +1929,10 @@ async def delete_app_profile( ] = None, *, name: Optional[str] = None, + ignore_warnings: Optional[bool] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes an app profile from an instance. @@ -1832,16 +1948,28 @@ async def delete_app_profile( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. + ignore_warnings (:class:`bool`): + Required. If true, ignore safety + checks when deleting the app profile. + + This corresponds to the ``ignore_warnings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name, ignore_warnings] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1857,6 +1985,8 @@ async def delete_app_profile( # request, apply these. if name is not None: request.name = name + if ignore_warnings is not None: + request.ignore_warnings = ignore_warnings # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1888,7 +2018,7 @@ async def get_iam_policy( resource: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Gets the access control policy for an instance resource. Returns an empty policy if an instance exists @@ -1909,8 +2039,10 @@ async def get_iam_policy( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.policy_pb2.Policy: @@ -1949,7 +2081,10 @@ async def get_iam_policy( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1996,7 +2131,7 @@ async def set_iam_policy( resource: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Sets the access control policy on an instance resource. Replaces any existing policy. @@ -2016,8 +2151,10 @@ async def set_iam_policy( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.policy_pb2.Policy: @@ -2056,7 +2193,10 @@ async def set_iam_policy( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2104,7 +2244,7 @@ async def test_iam_permissions( permissions: Optional[MutableSequence[str]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that the caller has on the specified instance resource. @@ -2133,8 +2273,10 @@ async def test_iam_permissions( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: @@ -2143,7 +2285,10 @@ async def test_iam_permissions( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) + flattened_params = [resource, permissions] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2194,7 +2339,7 @@ async def list_hot_tablets( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListHotTabletsAsyncPager: r"""Lists hot tablets in a cluster, within the time range provided. Hot tablets are ordered based on CPU usage. @@ -2214,8 +2359,10 @@ async def list_hot_tablets( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListHotTabletsAsyncPager: @@ -2229,7 +2376,10 @@ async def list_hot_tablets( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2283,6 +2433,1023 @@ async def list_hot_tablets( # Done; return the response. return response + async def create_logical_view( + self, + request: Optional[ + Union[bigtable_instance_admin.CreateLogicalViewRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + logical_view: Optional[instance.LogicalView] = None, + logical_view_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a logical view within an instance. + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.CreateLogicalViewRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.CreateLogicalView. + parent (:class:`str`): + Required. The parent instance where this logical view + will be created. Format: + ``projects/{project}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + logical_view (:class:`google.cloud.bigtable_admin_v2.types.LogicalView`): + Required. The logical view to create. + This corresponds to the ``logical_view`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + logical_view_id (:class:`str`): + Required. The ID to use for the + logical view, which will become the + final component of the logical view's + resource name. + + This corresponds to the ``logical_view_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.bigtable_admin_v2.types.LogicalView` + A SQL logical view object that can be referenced in SQL + queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, logical_view, logical_view_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.CreateLogicalViewRequest): + request = bigtable_instance_admin.CreateLogicalViewRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if logical_view is not None: + request.logical_view = logical_view + if logical_view_id is not None: + request.logical_view_id = logical_view_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_logical_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + instance.LogicalView, + metadata_type=bigtable_instance_admin.CreateLogicalViewMetadata, + ) + + # Done; return the response. + return response + + async def get_logical_view( + self, + request: Optional[ + Union[bigtable_instance_admin.GetLogicalViewRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.LogicalView: + r"""Gets information about a logical view. + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.GetLogicalViewRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.GetLogicalView. + name (:class:`str`): + Required. The unique name of the requested logical view. + Values are of the form + ``projects/{project}/instances/{instance}/logicalViews/{logical_view}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.types.LogicalView: + A SQL logical view object that can be + referenced in SQL queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.GetLogicalViewRequest): + request = bigtable_instance_admin.GetLogicalViewRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_logical_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_logical_views( + self, + request: Optional[ + Union[bigtable_instance_admin.ListLogicalViewsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogicalViewsAsyncPager: + r"""Lists information about logical views in an instance. + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.ListLogicalViewsRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.ListLogicalViews. + parent (:class:`str`): + Required. The unique name of the instance for which the + list of logical views is requested. Values are of the + form ``projects/{project}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListLogicalViewsAsyncPager: + Response message for + BigtableInstanceAdmin.ListLogicalViews. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.ListLogicalViewsRequest): + request = bigtable_instance_admin.ListLogicalViewsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_logical_views + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListLogicalViewsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_logical_view( + self, + request: Optional[ + Union[bigtable_instance_admin.UpdateLogicalViewRequest, dict] + ] = None, + *, + logical_view: Optional[instance.LogicalView] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a logical view within an instance. + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.UpdateLogicalViewRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.UpdateLogicalView. + logical_view (:class:`google.cloud.bigtable_admin_v2.types.LogicalView`): + Required. The logical view to update. + + The logical view's ``name`` field is used to identify + the view to update. Format: + ``projects/{project}/instances/{instance}/logicalViews/{logical_view}``. + + This corresponds to the ``logical_view`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.bigtable_admin_v2.types.LogicalView` + A SQL logical view object that can be referenced in SQL + queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [logical_view, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.UpdateLogicalViewRequest): + request = bigtable_instance_admin.UpdateLogicalViewRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if logical_view is not None: + request.logical_view = logical_view + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_logical_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("logical_view.name", request.logical_view.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + instance.LogicalView, + metadata_type=bigtable_instance_admin.UpdateLogicalViewMetadata, + ) + + # Done; return the response. + return response + + async def delete_logical_view( + self, + request: Optional[ + Union[bigtable_instance_admin.DeleteLogicalViewRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a logical view from an instance. + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.DeleteLogicalViewRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.DeleteLogicalView. + name (:class:`str`): + Required. The unique name of the logical view to be + deleted. Format: + ``projects/{project}/instances/{instance}/logicalViews/{logical_view}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.DeleteLogicalViewRequest): + request = bigtable_instance_admin.DeleteLogicalViewRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_logical_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_materialized_view( + self, + request: Optional[ + Union[bigtable_instance_admin.CreateMaterializedViewRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + materialized_view: Optional[instance.MaterializedView] = None, + materialized_view_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a materialized view within an instance. + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.CreateMaterializedViewRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.CreateMaterializedView. + parent (:class:`str`): + Required. The parent instance where this materialized + view will be created. Format: + ``projects/{project}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + materialized_view (:class:`google.cloud.bigtable_admin_v2.types.MaterializedView`): + Required. The materialized view to + create. + + This corresponds to the ``materialized_view`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + materialized_view_id (:class:`str`): + Required. The ID to use for the + materialized view, which will become the + final component of the materialized + view's resource name. + + This corresponds to the ``materialized_view_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.bigtable_admin_v2.types.MaterializedView` + A materialized view object that can be referenced in SQL + queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, materialized_view, materialized_view_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bigtable_instance_admin.CreateMaterializedViewRequest + ): + request = bigtable_instance_admin.CreateMaterializedViewRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if materialized_view is not None: + request.materialized_view = materialized_view + if materialized_view_id is not None: + request.materialized_view_id = materialized_view_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_materialized_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + instance.MaterializedView, + metadata_type=bigtable_instance_admin.CreateMaterializedViewMetadata, + ) + + # Done; return the response. + return response + + async def get_materialized_view( + self, + request: Optional[ + Union[bigtable_instance_admin.GetMaterializedViewRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.MaterializedView: + r"""Gets information about a materialized view. + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.GetMaterializedViewRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.GetMaterializedView. + name (:class:`str`): + Required. The unique name of the requested materialized + view. Values are of the form + ``projects/{project}/instances/{instance}/materializedViews/{materialized_view}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.types.MaterializedView: + A materialized view object that can + be referenced in SQL queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.GetMaterializedViewRequest): + request = bigtable_instance_admin.GetMaterializedViewRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_materialized_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_materialized_views( + self, + request: Optional[ + Union[bigtable_instance_admin.ListMaterializedViewsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMaterializedViewsAsyncPager: + r"""Lists information about materialized views in an + instance. + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.ListMaterializedViewsRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.ListMaterializedViews. + parent (:class:`str`): + Required. The unique name of the instance for which the + list of materialized views is requested. Values are of + the form ``projects/{project}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListMaterializedViewsAsyncPager: + Response message for + BigtableInstanceAdmin.ListMaterializedViews. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bigtable_instance_admin.ListMaterializedViewsRequest + ): + request = bigtable_instance_admin.ListMaterializedViewsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_materialized_views + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMaterializedViewsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_materialized_view( + self, + request: Optional[ + Union[bigtable_instance_admin.UpdateMaterializedViewRequest, dict] + ] = None, + *, + materialized_view: Optional[instance.MaterializedView] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a materialized view within an instance. + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.UpdateMaterializedViewRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.UpdateMaterializedView. + materialized_view (:class:`google.cloud.bigtable_admin_v2.types.MaterializedView`): + Required. The materialized view to update. + + The materialized view's ``name`` field is used to + identify the view to update. Format: + ``projects/{project}/instances/{instance}/materializedViews/{materialized_view}``. + + This corresponds to the ``materialized_view`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.bigtable_admin_v2.types.MaterializedView` + A materialized view object that can be referenced in SQL + queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [materialized_view, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bigtable_instance_admin.UpdateMaterializedViewRequest + ): + request = bigtable_instance_admin.UpdateMaterializedViewRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if materialized_view is not None: + request.materialized_view = materialized_view + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_materialized_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("materialized_view.name", request.materialized_view.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + instance.MaterializedView, + metadata_type=bigtable_instance_admin.UpdateMaterializedViewMetadata, + ) + + # Done; return the response. + return response + + async def delete_materialized_view( + self, + request: Optional[ + Union[bigtable_instance_admin.DeleteMaterializedViewRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a materialized view from an instance. + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.DeleteMaterializedViewRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.DeleteMaterializedView. + name (:class:`str`): + Required. The unique name of the materialized view to be + deleted. Format: + ``projects/{project}/instances/{instance}/materializedViews/{materialized_view}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bigtable_instance_admin.DeleteMaterializedViewRequest + ): + request = bigtable_instance_admin.DeleteMaterializedViewRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_materialized_view + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + async def __aenter__(self) -> "BigtableInstanceAdminAsyncClient": return self diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/client.py b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/client.py index b717eac8b..f96355156 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/client.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/client.py @@ -14,6 +14,9 @@ # limitations under the License. # from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging import os import re from typing import ( @@ -48,6 +51,15 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.bigtable_admin_v2.services.bigtable_instance_admin import pagers @@ -306,6 +318,50 @@ def parse_instance_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/instances/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def logical_view_path( + project: str, + instance: str, + logical_view: str, + ) -> str: + """Returns a fully-qualified logical_view string.""" + return "projects/{project}/instances/{instance}/logicalViews/{logical_view}".format( + project=project, + instance=instance, + logical_view=logical_view, + ) + + @staticmethod + def parse_logical_view_path(path: str) -> Dict[str, str]: + """Parses a logical_view path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/instances/(?P.+?)/logicalViews/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def materialized_view_path( + project: str, + instance: str, + materialized_view: str, + ) -> str: + """Returns a fully-qualified materialized_view string.""" + return "projects/{project}/instances/{instance}/materializedViews/{materialized_view}".format( + project=project, + instance=instance, + materialized_view=materialized_view, + ) + + @staticmethod + def parse_materialized_view_path(path: str) -> Dict[str, str]: + """Parses a materialized_view path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/instances/(?P.+?)/materializedViews/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def table_path( project: str, @@ -599,6 +655,33 @@ def _validate_universe_domain(self): # NOTE (b/349488459): universe validation is disabled until further notice. return True + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + @property def api_endpoint(self): """Return the API endpoint used by the client instance. @@ -707,6 +790,10 @@ def __init__( # Initialize the universe domain validation. self._is_universe_domain_valid = False + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: raise ValueError( @@ -773,6 +860,29 @@ def __init__( api_audience=self._client_options.api_audience, ) + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.bigtable.admin_v2.BigtableInstanceAdminClient`.", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "credentialsType": None, + }, + ) + def create_instance( self, request: Optional[ @@ -785,7 +895,7 @@ def create_instance( clusters: Optional[MutableMapping[str, gba_instance.Cluster]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Create an instance within a project. @@ -828,7 +938,6 @@ def create_instance( ``mycluster`` rather than ``projects/myproject/instances/myinstance/clusters/mycluster``. Fields marked ``OutputOnly`` must be left blank. - Currently, at most four clusters can be specified. This corresponds to the ``clusters`` field on the ``request`` instance; if ``request`` is provided, this @@ -836,8 +945,10 @@ def create_instance( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -853,7 +964,10 @@ def create_instance( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, instance_id, instance, clusters]) + flattened_params = [parent, instance_id, instance, clusters] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -916,7 +1030,7 @@ def get_instance( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.Instance: r"""Gets information about an instance. @@ -935,8 +1049,10 @@ def get_instance( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Instance: @@ -950,7 +1066,10 @@ def get_instance( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -999,7 +1118,7 @@ def list_instances( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_instance_admin.ListInstancesResponse: r"""Lists information about instances in a project. @@ -1018,8 +1137,10 @@ def list_instances( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.ListInstancesResponse: @@ -1030,7 +1151,10 @@ def list_instances( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1076,7 +1200,7 @@ def update_instance( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.Instance: r"""Updates an instance within a project. This method updates only the display name and type for an Instance. @@ -1094,8 +1218,10 @@ def update_instance( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Instance: @@ -1146,7 +1272,7 @@ def partial_update_instance( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Partially updates an instance within a project. This method can modify all fields of an Instance and is the @@ -1174,8 +1300,10 @@ def partial_update_instance( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1191,7 +1319,10 @@ def partial_update_instance( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([instance, update_mask]) + flattened_params = [instance, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1254,7 +1385,7 @@ def delete_instance( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Delete an instance from a project. @@ -1273,13 +1404,18 @@ def delete_instance( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1327,7 +1463,7 @@ def create_cluster( cluster: Optional[instance.Cluster] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Creates a cluster within an instance. @@ -1368,8 +1504,10 @@ def create_cluster( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1384,7 +1522,10 @@ def create_cluster( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, cluster_id, cluster]) + flattened_params = [parent, cluster_id, cluster] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1445,7 +1586,7 @@ def get_cluster( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.Cluster: r"""Gets information about a cluster. @@ -1464,8 +1605,10 @@ def get_cluster( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Cluster: @@ -1478,7 +1621,10 @@ def get_cluster( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1527,7 +1673,7 @@ def list_clusters( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_instance_admin.ListClustersResponse: r"""Lists information about clusters in an instance. @@ -1548,8 +1694,10 @@ def list_clusters( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.ListClustersResponse: @@ -1560,7 +1708,10 @@ def list_clusters( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1606,7 +1757,7 @@ def update_cluster( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Updates a cluster within an instance. @@ -1623,8 +1774,10 @@ def update_cluster( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1684,7 +1837,7 @@ def partial_update_cluster( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Partially updates a cluster within a project. This method is the preferred way to update a Cluster. @@ -1722,8 +1875,10 @@ def partial_update_cluster( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1738,7 +1893,10 @@ def partial_update_cluster( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([cluster, update_mask]) + flattened_params = [cluster, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1799,7 +1957,7 @@ def delete_cluster( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a cluster from an instance. @@ -1818,13 +1976,18 @@ def delete_cluster( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1872,7 +2035,7 @@ def create_app_profile( app_profile: Optional[instance.AppProfile] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.AppProfile: r"""Creates an app profile within an instance. @@ -1907,8 +2070,10 @@ def create_app_profile( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.AppProfile: @@ -1920,7 +2085,10 @@ def create_app_profile( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, app_profile_id, app_profile]) + flattened_params = [parent, app_profile_id, app_profile] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1973,7 +2141,7 @@ def get_app_profile( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.AppProfile: r"""Gets information about an app profile. @@ -1992,8 +2160,10 @@ def get_app_profile( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.AppProfile: @@ -2005,7 +2175,10 @@ def get_app_profile( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2054,7 +2227,7 @@ def list_app_profiles( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAppProfilesPager: r"""Lists information about app profiles in an instance. @@ -2076,8 +2249,10 @@ def list_app_profiles( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListAppProfilesPager: @@ -2091,7 +2266,10 @@ def list_app_profiles( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2152,7 +2330,7 @@ def update_app_profile( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Updates an app profile within an instance. @@ -2178,8 +2356,10 @@ def update_app_profile( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -2192,7 +2372,10 @@ def update_app_profile( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([app_profile, update_mask]) + flattened_params = [app_profile, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2251,9 +2434,10 @@ def delete_app_profile( ] = None, *, name: Optional[str] = None, + ignore_warnings: Optional[bool] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes an app profile from an instance. @@ -2269,16 +2453,28 @@ def delete_app_profile( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. + ignore_warnings (bool): + Required. If true, ignore safety + checks when deleting the app profile. + + This corresponds to the ``ignore_warnings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name, ignore_warnings] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2293,6 +2489,8 @@ def delete_app_profile( # request, apply these. if name is not None: request.name = name + if ignore_warnings is not None: + request.ignore_warnings = ignore_warnings # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2322,7 +2520,7 @@ def get_iam_policy( resource: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Gets the access control policy for an instance resource. Returns an empty policy if an instance exists @@ -2343,8 +2541,10 @@ def get_iam_policy( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.policy_pb2.Policy: @@ -2383,7 +2583,10 @@ def get_iam_policy( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2431,7 +2634,7 @@ def set_iam_policy( resource: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Sets the access control policy on an instance resource. Replaces any existing policy. @@ -2451,8 +2654,10 @@ def set_iam_policy( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.policy_pb2.Policy: @@ -2491,7 +2696,10 @@ def set_iam_policy( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2540,7 +2748,7 @@ def test_iam_permissions( permissions: Optional[MutableSequence[str]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that the caller has on the specified instance resource. @@ -2569,8 +2777,10 @@ def test_iam_permissions( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: @@ -2579,7 +2789,10 @@ def test_iam_permissions( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) + flattened_params = [resource, permissions] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2631,7 +2844,7 @@ def list_hot_tablets( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListHotTabletsPager: r"""Lists hot tablets in a cluster, within the time range provided. Hot tablets are ordered based on CPU usage. @@ -2651,8 +2864,10 @@ def list_hot_tablets( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListHotTabletsPager: @@ -2666,7 +2881,10 @@ def list_hot_tablets( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2717,6 +2935,993 @@ def list_hot_tablets( # Done; return the response. return response + def create_logical_view( + self, + request: Optional[ + Union[bigtable_instance_admin.CreateLogicalViewRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + logical_view: Optional[instance.LogicalView] = None, + logical_view_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a logical view within an instance. + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.CreateLogicalViewRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.CreateLogicalView. + parent (str): + Required. The parent instance where this logical view + will be created. Format: + ``projects/{project}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + logical_view (google.cloud.bigtable_admin_v2.types.LogicalView): + Required. The logical view to create. + This corresponds to the ``logical_view`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + logical_view_id (str): + Required. The ID to use for the + logical view, which will become the + final component of the logical view's + resource name. + + This corresponds to the ``logical_view_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.bigtable_admin_v2.types.LogicalView` + A SQL logical view object that can be referenced in SQL + queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, logical_view, logical_view_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.CreateLogicalViewRequest): + request = bigtable_instance_admin.CreateLogicalViewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if logical_view is not None: + request.logical_view = logical_view + if logical_view_id is not None: + request.logical_view_id = logical_view_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_logical_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + instance.LogicalView, + metadata_type=bigtable_instance_admin.CreateLogicalViewMetadata, + ) + + # Done; return the response. + return response + + def get_logical_view( + self, + request: Optional[ + Union[bigtable_instance_admin.GetLogicalViewRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.LogicalView: + r"""Gets information about a logical view. + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.GetLogicalViewRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.GetLogicalView. + name (str): + Required. The unique name of the requested logical view. + Values are of the form + ``projects/{project}/instances/{instance}/logicalViews/{logical_view}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.types.LogicalView: + A SQL logical view object that can be + referenced in SQL queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.GetLogicalViewRequest): + request = bigtable_instance_admin.GetLogicalViewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_logical_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_logical_views( + self, + request: Optional[ + Union[bigtable_instance_admin.ListLogicalViewsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogicalViewsPager: + r"""Lists information about logical views in an instance. + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.ListLogicalViewsRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.ListLogicalViews. + parent (str): + Required. The unique name of the instance for which the + list of logical views is requested. Values are of the + form ``projects/{project}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListLogicalViewsPager: + Response message for + BigtableInstanceAdmin.ListLogicalViews. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.ListLogicalViewsRequest): + request = bigtable_instance_admin.ListLogicalViewsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_logical_views] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListLogicalViewsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_logical_view( + self, + request: Optional[ + Union[bigtable_instance_admin.UpdateLogicalViewRequest, dict] + ] = None, + *, + logical_view: Optional[instance.LogicalView] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a logical view within an instance. + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.UpdateLogicalViewRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.UpdateLogicalView. + logical_view (google.cloud.bigtable_admin_v2.types.LogicalView): + Required. The logical view to update. + + The logical view's ``name`` field is used to identify + the view to update. Format: + ``projects/{project}/instances/{instance}/logicalViews/{logical_view}``. + + This corresponds to the ``logical_view`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.bigtable_admin_v2.types.LogicalView` + A SQL logical view object that can be referenced in SQL + queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [logical_view, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.UpdateLogicalViewRequest): + request = bigtable_instance_admin.UpdateLogicalViewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if logical_view is not None: + request.logical_view = logical_view + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_logical_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("logical_view.name", request.logical_view.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + instance.LogicalView, + metadata_type=bigtable_instance_admin.UpdateLogicalViewMetadata, + ) + + # Done; return the response. + return response + + def delete_logical_view( + self, + request: Optional[ + Union[bigtable_instance_admin.DeleteLogicalViewRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a logical view from an instance. + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.DeleteLogicalViewRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.DeleteLogicalView. + name (str): + Required. The unique name of the logical view to be + deleted. Format: + ``projects/{project}/instances/{instance}/logicalViews/{logical_view}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.DeleteLogicalViewRequest): + request = bigtable_instance_admin.DeleteLogicalViewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_logical_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_materialized_view( + self, + request: Optional[ + Union[bigtable_instance_admin.CreateMaterializedViewRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + materialized_view: Optional[instance.MaterializedView] = None, + materialized_view_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a materialized view within an instance. + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.CreateMaterializedViewRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.CreateMaterializedView. + parent (str): + Required. The parent instance where this materialized + view will be created. Format: + ``projects/{project}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + materialized_view (google.cloud.bigtable_admin_v2.types.MaterializedView): + Required. The materialized view to + create. + + This corresponds to the ``materialized_view`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + materialized_view_id (str): + Required. The ID to use for the + materialized view, which will become the + final component of the materialized + view's resource name. + + This corresponds to the ``materialized_view_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.bigtable_admin_v2.types.MaterializedView` + A materialized view object that can be referenced in SQL + queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, materialized_view, materialized_view_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bigtable_instance_admin.CreateMaterializedViewRequest + ): + request = bigtable_instance_admin.CreateMaterializedViewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if materialized_view is not None: + request.materialized_view = materialized_view + if materialized_view_id is not None: + request.materialized_view_id = materialized_view_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_materialized_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + instance.MaterializedView, + metadata_type=bigtable_instance_admin.CreateMaterializedViewMetadata, + ) + + # Done; return the response. + return response + + def get_materialized_view( + self, + request: Optional[ + Union[bigtable_instance_admin.GetMaterializedViewRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.MaterializedView: + r"""Gets information about a materialized view. + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.GetMaterializedViewRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.GetMaterializedView. + name (str): + Required. The unique name of the requested materialized + view. Values are of the form + ``projects/{project}/instances/{instance}/materializedViews/{materialized_view}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.types.MaterializedView: + A materialized view object that can + be referenced in SQL queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.GetMaterializedViewRequest): + request = bigtable_instance_admin.GetMaterializedViewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_materialized_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_materialized_views( + self, + request: Optional[ + Union[bigtable_instance_admin.ListMaterializedViewsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMaterializedViewsPager: + r"""Lists information about materialized views in an + instance. + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.ListMaterializedViewsRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.ListMaterializedViews. + parent (str): + Required. The unique name of the instance for which the + list of materialized views is requested. Values are of + the form ``projects/{project}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListMaterializedViewsPager: + Response message for + BigtableInstanceAdmin.ListMaterializedViews. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bigtable_instance_admin.ListMaterializedViewsRequest + ): + request = bigtable_instance_admin.ListMaterializedViewsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_materialized_views] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMaterializedViewsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_materialized_view( + self, + request: Optional[ + Union[bigtable_instance_admin.UpdateMaterializedViewRequest, dict] + ] = None, + *, + materialized_view: Optional[instance.MaterializedView] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a materialized view within an instance. + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.UpdateMaterializedViewRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.UpdateMaterializedView. + materialized_view (google.cloud.bigtable_admin_v2.types.MaterializedView): + Required. The materialized view to update. + + The materialized view's ``name`` field is used to + identify the view to update. Format: + ``projects/{project}/instances/{instance}/materializedViews/{materialized_view}``. + + This corresponds to the ``materialized_view`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.bigtable_admin_v2.types.MaterializedView` + A materialized view object that can be referenced in SQL + queries. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [materialized_view, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bigtable_instance_admin.UpdateMaterializedViewRequest + ): + request = bigtable_instance_admin.UpdateMaterializedViewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if materialized_view is not None: + request.materialized_view = materialized_view + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_materialized_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("materialized_view.name", request.materialized_view.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + instance.MaterializedView, + metadata_type=bigtable_instance_admin.UpdateMaterializedViewMetadata, + ) + + # Done; return the response. + return response + + def delete_materialized_view( + self, + request: Optional[ + Union[bigtable_instance_admin.DeleteMaterializedViewRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a materialized view from an instance. + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.DeleteMaterializedViewRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.DeleteMaterializedView. + name (str): + Required. The unique name of the materialized view to be + deleted. Format: + ``projects/{project}/instances/{instance}/materializedViews/{materialized_view}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bigtable_instance_admin.DeleteMaterializedViewRequest + ): + request = bigtable_instance_admin.DeleteMaterializedViewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_materialized_view] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + def __enter__(self) -> "BigtableInstanceAdminClient": return self diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/pagers.py b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/pagers.py index bb7ee001f..355d641e4 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/pagers.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_instance_admin.ListAppProfilesRequest(request) @@ -143,7 +145,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -157,8 +159,10 @@ def __init__( retry (google.api_core.retry.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_instance_admin.ListAppProfilesRequest(request) @@ -223,7 +227,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -237,8 +241,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_instance_admin.ListHotTabletsRequest(request) @@ -299,7 +305,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -313,8 +319,10 @@ def __init__( retry (google.api_core.retry.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_instance_admin.ListHotTabletsRequest(request) @@ -351,3 +359,323 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLogicalViewsPager: + """A pager for iterating through ``list_logical_views`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigtable_admin_v2.types.ListLogicalViewsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``logical_views`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLogicalViews`` requests and continue to iterate + through the ``logical_views`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigtable_admin_v2.types.ListLogicalViewsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., bigtable_instance_admin.ListLogicalViewsResponse], + request: bigtable_instance_admin.ListLogicalViewsRequest, + response: bigtable_instance_admin.ListLogicalViewsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.bigtable_admin_v2.types.ListLogicalViewsRequest): + The initial request object. + response (google.cloud.bigtable_admin_v2.types.ListLogicalViewsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = bigtable_instance_admin.ListLogicalViewsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[bigtable_instance_admin.ListLogicalViewsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[instance.LogicalView]: + for page in self.pages: + yield from page.logical_views + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLogicalViewsAsyncPager: + """A pager for iterating through ``list_logical_views`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigtable_admin_v2.types.ListLogicalViewsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``logical_views`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLogicalViews`` requests and continue to iterate + through the ``logical_views`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigtable_admin_v2.types.ListLogicalViewsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[bigtable_instance_admin.ListLogicalViewsResponse] + ], + request: bigtable_instance_admin.ListLogicalViewsRequest, + response: bigtable_instance_admin.ListLogicalViewsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.bigtable_admin_v2.types.ListLogicalViewsRequest): + The initial request object. + response (google.cloud.bigtable_admin_v2.types.ListLogicalViewsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = bigtable_instance_admin.ListLogicalViewsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[bigtable_instance_admin.ListLogicalViewsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[instance.LogicalView]: + async def async_generator(): + async for page in self.pages: + for response in page.logical_views: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMaterializedViewsPager: + """A pager for iterating through ``list_materialized_views`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigtable_admin_v2.types.ListMaterializedViewsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``materialized_views`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMaterializedViews`` requests and continue to iterate + through the ``materialized_views`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigtable_admin_v2.types.ListMaterializedViewsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., bigtable_instance_admin.ListMaterializedViewsResponse], + request: bigtable_instance_admin.ListMaterializedViewsRequest, + response: bigtable_instance_admin.ListMaterializedViewsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.bigtable_admin_v2.types.ListMaterializedViewsRequest): + The initial request object. + response (google.cloud.bigtable_admin_v2.types.ListMaterializedViewsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = bigtable_instance_admin.ListMaterializedViewsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[bigtable_instance_admin.ListMaterializedViewsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[instance.MaterializedView]: + for page in self.pages: + yield from page.materialized_views + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMaterializedViewsAsyncPager: + """A pager for iterating through ``list_materialized_views`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigtable_admin_v2.types.ListMaterializedViewsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``materialized_views`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMaterializedViews`` requests and continue to iterate + through the ``materialized_views`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigtable_admin_v2.types.ListMaterializedViewsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[bigtable_instance_admin.ListMaterializedViewsResponse] + ], + request: bigtable_instance_admin.ListMaterializedViewsRequest, + response: bigtable_instance_admin.ListMaterializedViewsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.bigtable_admin_v2.types.ListMaterializedViewsRequest): + The initial request object. + response (google.cloud.bigtable_admin_v2.types.ListMaterializedViewsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = bigtable_instance_admin.ListMaterializedViewsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[bigtable_instance_admin.ListMaterializedViewsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[instance.MaterializedView]: + async def async_generator(): + async for page in self.pages: + for response in page.materialized_views: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/base.py b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/base.py index bc2f819b8..f2576c676 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/base.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/base.py @@ -378,6 +378,56 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.create_logical_view: gapic_v1.method.wrap_method( + self.create_logical_view, + default_timeout=None, + client_info=client_info, + ), + self.get_logical_view: gapic_v1.method.wrap_method( + self.get_logical_view, + default_timeout=None, + client_info=client_info, + ), + self.list_logical_views: gapic_v1.method.wrap_method( + self.list_logical_views, + default_timeout=None, + client_info=client_info, + ), + self.update_logical_view: gapic_v1.method.wrap_method( + self.update_logical_view, + default_timeout=None, + client_info=client_info, + ), + self.delete_logical_view: gapic_v1.method.wrap_method( + self.delete_logical_view, + default_timeout=None, + client_info=client_info, + ), + self.create_materialized_view: gapic_v1.method.wrap_method( + self.create_materialized_view, + default_timeout=None, + client_info=client_info, + ), + self.get_materialized_view: gapic_v1.method.wrap_method( + self.get_materialized_view, + default_timeout=None, + client_info=client_info, + ), + self.list_materialized_views: gapic_v1.method.wrap_method( + self.list_materialized_views, + default_timeout=None, + client_info=client_info, + ), + self.update_materialized_view: gapic_v1.method.wrap_method( + self.update_materialized_view, + default_timeout=None, + client_info=client_info, + ), + self.delete_materialized_view: gapic_v1.method.wrap_method( + self.delete_materialized_view, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -597,6 +647,102 @@ def list_hot_tablets( ]: raise NotImplementedError() + @property + def create_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.CreateLogicalViewRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.GetLogicalViewRequest], + Union[instance.LogicalView, Awaitable[instance.LogicalView]], + ]: + raise NotImplementedError() + + @property + def list_logical_views( + self, + ) -> Callable[ + [bigtable_instance_admin.ListLogicalViewsRequest], + Union[ + bigtable_instance_admin.ListLogicalViewsResponse, + Awaitable[bigtable_instance_admin.ListLogicalViewsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateLogicalViewRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.DeleteLogicalViewRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def create_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.CreateMaterializedViewRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.GetMaterializedViewRequest], + Union[instance.MaterializedView, Awaitable[instance.MaterializedView]], + ]: + raise NotImplementedError() + + @property + def list_materialized_views( + self, + ) -> Callable[ + [bigtable_instance_admin.ListMaterializedViewsRequest], + Union[ + bigtable_instance_admin.ListMaterializedViewsResponse, + Awaitable[bigtable_instance_admin.ListMaterializedViewsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateMaterializedViewRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.DeleteMaterializedViewRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc.py b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc.py index cc3e70986..eb13e683b 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union @@ -22,8 +25,11 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message import grpc # type: ignore +import proto # type: ignore from google.cloud.bigtable_admin_v2.types import bigtable_instance_admin from google.cloud.bigtable_admin_v2.types import instance @@ -33,6 +39,81 @@ from google.protobuf import empty_pb2 # type: ignore from .base import BigtableInstanceAdminTransport, DEFAULT_CLIENT_INFO +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class BigtableInstanceAdminGrpcTransport(BigtableInstanceAdminTransport): """gRPC backend transport for BigtableInstanceAdmin. @@ -190,7 +271,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod @@ -254,7 +340,9 @@ def operations_client(self) -> operations_v1.OperationsClient: """ # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) # Return the client from cache. return self._operations_client @@ -286,7 +374,7 @@ def create_instance( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_instance" not in self._stubs: - self._stubs["create_instance"] = self.grpc_channel.unary_unary( + self._stubs["create_instance"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/CreateInstance", request_serializer=bigtable_instance_admin.CreateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -312,7 +400,7 @@ def get_instance( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_instance" not in self._stubs: - self._stubs["get_instance"] = self.grpc_channel.unary_unary( + self._stubs["get_instance"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetInstance", request_serializer=bigtable_instance_admin.GetInstanceRequest.serialize, response_deserializer=instance.Instance.deserialize, @@ -341,7 +429,7 @@ def list_instances( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_instances" not in self._stubs: - self._stubs["list_instances"] = self.grpc_channel.unary_unary( + self._stubs["list_instances"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListInstances", request_serializer=bigtable_instance_admin.ListInstancesRequest.serialize, response_deserializer=bigtable_instance_admin.ListInstancesResponse.deserialize, @@ -368,7 +456,7 @@ def update_instance(self) -> Callable[[instance.Instance], instance.Instance]: # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_instance" not in self._stubs: - self._stubs["update_instance"] = self.grpc_channel.unary_unary( + self._stubs["update_instance"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateInstance", request_serializer=instance.Instance.serialize, response_deserializer=instance.Instance.deserialize, @@ -398,7 +486,7 @@ def partial_update_instance( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "partial_update_instance" not in self._stubs: - self._stubs["partial_update_instance"] = self.grpc_channel.unary_unary( + self._stubs["partial_update_instance"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/PartialUpdateInstance", request_serializer=bigtable_instance_admin.PartialUpdateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -424,7 +512,7 @@ def delete_instance( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_instance" not in self._stubs: - self._stubs["delete_instance"] = self.grpc_channel.unary_unary( + self._stubs["delete_instance"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/DeleteInstance", request_serializer=bigtable_instance_admin.DeleteInstanceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -458,7 +546,7 @@ def create_cluster( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_cluster" not in self._stubs: - self._stubs["create_cluster"] = self.grpc_channel.unary_unary( + self._stubs["create_cluster"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/CreateCluster", request_serializer=bigtable_instance_admin.CreateClusterRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -484,7 +572,7 @@ def get_cluster( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_cluster" not in self._stubs: - self._stubs["get_cluster"] = self.grpc_channel.unary_unary( + self._stubs["get_cluster"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetCluster", request_serializer=bigtable_instance_admin.GetClusterRequest.serialize, response_deserializer=instance.Cluster.deserialize, @@ -513,7 +601,7 @@ def list_clusters( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_clusters" not in self._stubs: - self._stubs["list_clusters"] = self.grpc_channel.unary_unary( + self._stubs["list_clusters"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListClusters", request_serializer=bigtable_instance_admin.ListClustersRequest.serialize, response_deserializer=bigtable_instance_admin.ListClustersResponse.deserialize, @@ -541,7 +629,7 @@ def update_cluster(self) -> Callable[[instance.Cluster], operations_pb2.Operatio # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_cluster" not in self._stubs: - self._stubs["update_cluster"] = self.grpc_channel.unary_unary( + self._stubs["update_cluster"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateCluster", request_serializer=instance.Cluster.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -582,7 +670,7 @@ def partial_update_cluster( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "partial_update_cluster" not in self._stubs: - self._stubs["partial_update_cluster"] = self.grpc_channel.unary_unary( + self._stubs["partial_update_cluster"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/PartialUpdateCluster", request_serializer=bigtable_instance_admin.PartialUpdateClusterRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -608,7 +696,7 @@ def delete_cluster( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_cluster" not in self._stubs: - self._stubs["delete_cluster"] = self.grpc_channel.unary_unary( + self._stubs["delete_cluster"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/DeleteCluster", request_serializer=bigtable_instance_admin.DeleteClusterRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -636,7 +724,7 @@ def create_app_profile( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_app_profile" not in self._stubs: - self._stubs["create_app_profile"] = self.grpc_channel.unary_unary( + self._stubs["create_app_profile"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/CreateAppProfile", request_serializer=bigtable_instance_admin.CreateAppProfileRequest.serialize, response_deserializer=instance.AppProfile.deserialize, @@ -662,7 +750,7 @@ def get_app_profile( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_app_profile" not in self._stubs: - self._stubs["get_app_profile"] = self.grpc_channel.unary_unary( + self._stubs["get_app_profile"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetAppProfile", request_serializer=bigtable_instance_admin.GetAppProfileRequest.serialize, response_deserializer=instance.AppProfile.deserialize, @@ -691,7 +779,7 @@ def list_app_profiles( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_app_profiles" not in self._stubs: - self._stubs["list_app_profiles"] = self.grpc_channel.unary_unary( + self._stubs["list_app_profiles"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListAppProfiles", request_serializer=bigtable_instance_admin.ListAppProfilesRequest.serialize, response_deserializer=bigtable_instance_admin.ListAppProfilesResponse.deserialize, @@ -719,7 +807,7 @@ def update_app_profile( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_app_profile" not in self._stubs: - self._stubs["update_app_profile"] = self.grpc_channel.unary_unary( + self._stubs["update_app_profile"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateAppProfile", request_serializer=bigtable_instance_admin.UpdateAppProfileRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -745,7 +833,7 @@ def delete_app_profile( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_app_profile" not in self._stubs: - self._stubs["delete_app_profile"] = self.grpc_channel.unary_unary( + self._stubs["delete_app_profile"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/DeleteAppProfile", request_serializer=bigtable_instance_admin.DeleteAppProfileRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -773,7 +861,7 @@ def get_iam_policy( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetIamPolicy", request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -800,7 +888,7 @@ def set_iam_policy( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/SetIamPolicy", request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -830,7 +918,7 @@ def test_iam_permissions( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/TestIamPermissions", request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, @@ -860,15 +948,298 @@ def list_hot_tablets( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_hot_tablets" not in self._stubs: - self._stubs["list_hot_tablets"] = self.grpc_channel.unary_unary( + self._stubs["list_hot_tablets"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListHotTablets", request_serializer=bigtable_instance_admin.ListHotTabletsRequest.serialize, response_deserializer=bigtable_instance_admin.ListHotTabletsResponse.deserialize, ) return self._stubs["list_hot_tablets"] + @property + def create_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.CreateLogicalViewRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create logical view method over gRPC. + + Creates a logical view within an instance. + + Returns: + Callable[[~.CreateLogicalViewRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_logical_view" not in self._stubs: + self._stubs["create_logical_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/CreateLogicalView", + request_serializer=bigtable_instance_admin.CreateLogicalViewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_logical_view"] + + @property + def get_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.GetLogicalViewRequest], instance.LogicalView + ]: + r"""Return a callable for the get logical view method over gRPC. + + Gets information about a logical view. + + Returns: + Callable[[~.GetLogicalViewRequest], + ~.LogicalView]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_logical_view" not in self._stubs: + self._stubs["get_logical_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetLogicalView", + request_serializer=bigtable_instance_admin.GetLogicalViewRequest.serialize, + response_deserializer=instance.LogicalView.deserialize, + ) + return self._stubs["get_logical_view"] + + @property + def list_logical_views( + self, + ) -> Callable[ + [bigtable_instance_admin.ListLogicalViewsRequest], + bigtable_instance_admin.ListLogicalViewsResponse, + ]: + r"""Return a callable for the list logical views method over gRPC. + + Lists information about logical views in an instance. + + Returns: + Callable[[~.ListLogicalViewsRequest], + ~.ListLogicalViewsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_logical_views" not in self._stubs: + self._stubs["list_logical_views"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListLogicalViews", + request_serializer=bigtable_instance_admin.ListLogicalViewsRequest.serialize, + response_deserializer=bigtable_instance_admin.ListLogicalViewsResponse.deserialize, + ) + return self._stubs["list_logical_views"] + + @property + def update_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateLogicalViewRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update logical view method over gRPC. + + Updates a logical view within an instance. + + Returns: + Callable[[~.UpdateLogicalViewRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_logical_view" not in self._stubs: + self._stubs["update_logical_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateLogicalView", + request_serializer=bigtable_instance_admin.UpdateLogicalViewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_logical_view"] + + @property + def delete_logical_view( + self, + ) -> Callable[[bigtable_instance_admin.DeleteLogicalViewRequest], empty_pb2.Empty]: + r"""Return a callable for the delete logical view method over gRPC. + + Deletes a logical view from an instance. + + Returns: + Callable[[~.DeleteLogicalViewRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_logical_view" not in self._stubs: + self._stubs["delete_logical_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/DeleteLogicalView", + request_serializer=bigtable_instance_admin.DeleteLogicalViewRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_logical_view"] + + @property + def create_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.CreateMaterializedViewRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create materialized view method over gRPC. + + Creates a materialized view within an instance. + + Returns: + Callable[[~.CreateMaterializedViewRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_materialized_view" not in self._stubs: + self._stubs["create_materialized_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/CreateMaterializedView", + request_serializer=bigtable_instance_admin.CreateMaterializedViewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_materialized_view"] + + @property + def get_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.GetMaterializedViewRequest], instance.MaterializedView + ]: + r"""Return a callable for the get materialized view method over gRPC. + + Gets information about a materialized view. + + Returns: + Callable[[~.GetMaterializedViewRequest], + ~.MaterializedView]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_materialized_view" not in self._stubs: + self._stubs["get_materialized_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetMaterializedView", + request_serializer=bigtable_instance_admin.GetMaterializedViewRequest.serialize, + response_deserializer=instance.MaterializedView.deserialize, + ) + return self._stubs["get_materialized_view"] + + @property + def list_materialized_views( + self, + ) -> Callable[ + [bigtable_instance_admin.ListMaterializedViewsRequest], + bigtable_instance_admin.ListMaterializedViewsResponse, + ]: + r"""Return a callable for the list materialized views method over gRPC. + + Lists information about materialized views in an + instance. + + Returns: + Callable[[~.ListMaterializedViewsRequest], + ~.ListMaterializedViewsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_materialized_views" not in self._stubs: + self._stubs["list_materialized_views"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListMaterializedViews", + request_serializer=bigtable_instance_admin.ListMaterializedViewsRequest.serialize, + response_deserializer=bigtable_instance_admin.ListMaterializedViewsResponse.deserialize, + ) + return self._stubs["list_materialized_views"] + + @property + def update_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateMaterializedViewRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the update materialized view method over gRPC. + + Updates a materialized view within an instance. + + Returns: + Callable[[~.UpdateMaterializedViewRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_materialized_view" not in self._stubs: + self._stubs["update_materialized_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateMaterializedView", + request_serializer=bigtable_instance_admin.UpdateMaterializedViewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_materialized_view"] + + @property + def delete_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.DeleteMaterializedViewRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete materialized view method over gRPC. + + Deletes a materialized view from an instance. + + Returns: + Callable[[~.DeleteMaterializedViewRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_materialized_view" not in self._stubs: + self._stubs["delete_materialized_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/DeleteMaterializedView", + request_serializer=bigtable_instance_admin.DeleteMaterializedViewRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_materialized_view"] + def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc_asyncio.py b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc_asyncio.py index 716e14a86..12e63f7fe 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc_asyncio.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import pickle +import logging as std_logging import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union @@ -24,8 +27,11 @@ from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.bigtable_admin_v2.types import bigtable_instance_admin @@ -37,6 +43,82 @@ from .base import BigtableInstanceAdminTransport, DEFAULT_CLIENT_INFO from .grpc import BigtableInstanceAdminGrpcTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class BigtableInstanceAdminGrpcAsyncIOTransport(BigtableInstanceAdminTransport): """gRPC AsyncIO backend transport for BigtableInstanceAdmin. @@ -237,10 +319,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel self._wrap_with_kind = ( "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters ) + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @property @@ -263,7 +348,7 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel + self._logged_channel ) # Return the client from cache. @@ -297,7 +382,7 @@ def create_instance( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_instance" not in self._stubs: - self._stubs["create_instance"] = self.grpc_channel.unary_unary( + self._stubs["create_instance"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/CreateInstance", request_serializer=bigtable_instance_admin.CreateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -325,7 +410,7 @@ def get_instance( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_instance" not in self._stubs: - self._stubs["get_instance"] = self.grpc_channel.unary_unary( + self._stubs["get_instance"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetInstance", request_serializer=bigtable_instance_admin.GetInstanceRequest.serialize, response_deserializer=instance.Instance.deserialize, @@ -354,7 +439,7 @@ def list_instances( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_instances" not in self._stubs: - self._stubs["list_instances"] = self.grpc_channel.unary_unary( + self._stubs["list_instances"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListInstances", request_serializer=bigtable_instance_admin.ListInstancesRequest.serialize, response_deserializer=bigtable_instance_admin.ListInstancesResponse.deserialize, @@ -383,7 +468,7 @@ def update_instance( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_instance" not in self._stubs: - self._stubs["update_instance"] = self.grpc_channel.unary_unary( + self._stubs["update_instance"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateInstance", request_serializer=instance.Instance.serialize, response_deserializer=instance.Instance.deserialize, @@ -414,7 +499,7 @@ def partial_update_instance( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "partial_update_instance" not in self._stubs: - self._stubs["partial_update_instance"] = self.grpc_channel.unary_unary( + self._stubs["partial_update_instance"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/PartialUpdateInstance", request_serializer=bigtable_instance_admin.PartialUpdateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -442,7 +527,7 @@ def delete_instance( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_instance" not in self._stubs: - self._stubs["delete_instance"] = self.grpc_channel.unary_unary( + self._stubs["delete_instance"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/DeleteInstance", request_serializer=bigtable_instance_admin.DeleteInstanceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -477,7 +562,7 @@ def create_cluster( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_cluster" not in self._stubs: - self._stubs["create_cluster"] = self.grpc_channel.unary_unary( + self._stubs["create_cluster"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/CreateCluster", request_serializer=bigtable_instance_admin.CreateClusterRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -505,7 +590,7 @@ def get_cluster( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_cluster" not in self._stubs: - self._stubs["get_cluster"] = self.grpc_channel.unary_unary( + self._stubs["get_cluster"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetCluster", request_serializer=bigtable_instance_admin.GetClusterRequest.serialize, response_deserializer=instance.Cluster.deserialize, @@ -534,7 +619,7 @@ def list_clusters( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_clusters" not in self._stubs: - self._stubs["list_clusters"] = self.grpc_channel.unary_unary( + self._stubs["list_clusters"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListClusters", request_serializer=bigtable_instance_admin.ListClustersRequest.serialize, response_deserializer=bigtable_instance_admin.ListClustersResponse.deserialize, @@ -564,7 +649,7 @@ def update_cluster( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_cluster" not in self._stubs: - self._stubs["update_cluster"] = self.grpc_channel.unary_unary( + self._stubs["update_cluster"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateCluster", request_serializer=instance.Cluster.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -606,7 +691,7 @@ def partial_update_cluster( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "partial_update_cluster" not in self._stubs: - self._stubs["partial_update_cluster"] = self.grpc_channel.unary_unary( + self._stubs["partial_update_cluster"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/PartialUpdateCluster", request_serializer=bigtable_instance_admin.PartialUpdateClusterRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -634,7 +719,7 @@ def delete_cluster( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_cluster" not in self._stubs: - self._stubs["delete_cluster"] = self.grpc_channel.unary_unary( + self._stubs["delete_cluster"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/DeleteCluster", request_serializer=bigtable_instance_admin.DeleteClusterRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -663,7 +748,7 @@ def create_app_profile( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_app_profile" not in self._stubs: - self._stubs["create_app_profile"] = self.grpc_channel.unary_unary( + self._stubs["create_app_profile"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/CreateAppProfile", request_serializer=bigtable_instance_admin.CreateAppProfileRequest.serialize, response_deserializer=instance.AppProfile.deserialize, @@ -691,7 +776,7 @@ def get_app_profile( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_app_profile" not in self._stubs: - self._stubs["get_app_profile"] = self.grpc_channel.unary_unary( + self._stubs["get_app_profile"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetAppProfile", request_serializer=bigtable_instance_admin.GetAppProfileRequest.serialize, response_deserializer=instance.AppProfile.deserialize, @@ -720,7 +805,7 @@ def list_app_profiles( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_app_profiles" not in self._stubs: - self._stubs["list_app_profiles"] = self.grpc_channel.unary_unary( + self._stubs["list_app_profiles"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListAppProfiles", request_serializer=bigtable_instance_admin.ListAppProfilesRequest.serialize, response_deserializer=bigtable_instance_admin.ListAppProfilesResponse.deserialize, @@ -749,7 +834,7 @@ def update_app_profile( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_app_profile" not in self._stubs: - self._stubs["update_app_profile"] = self.grpc_channel.unary_unary( + self._stubs["update_app_profile"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateAppProfile", request_serializer=bigtable_instance_admin.UpdateAppProfileRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -777,7 +862,7 @@ def delete_app_profile( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_app_profile" not in self._stubs: - self._stubs["delete_app_profile"] = self.grpc_channel.unary_unary( + self._stubs["delete_app_profile"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/DeleteAppProfile", request_serializer=bigtable_instance_admin.DeleteAppProfileRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -805,7 +890,7 @@ def get_iam_policy( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetIamPolicy", request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -832,7 +917,7 @@ def set_iam_policy( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/SetIamPolicy", request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -862,7 +947,7 @@ def test_iam_permissions( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/TestIamPermissions", request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, @@ -892,13 +977,302 @@ def list_hot_tablets( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_hot_tablets" not in self._stubs: - self._stubs["list_hot_tablets"] = self.grpc_channel.unary_unary( + self._stubs["list_hot_tablets"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListHotTablets", request_serializer=bigtable_instance_admin.ListHotTabletsRequest.serialize, response_deserializer=bigtable_instance_admin.ListHotTabletsResponse.deserialize, ) return self._stubs["list_hot_tablets"] + @property + def create_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.CreateLogicalViewRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create logical view method over gRPC. + + Creates a logical view within an instance. + + Returns: + Callable[[~.CreateLogicalViewRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_logical_view" not in self._stubs: + self._stubs["create_logical_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/CreateLogicalView", + request_serializer=bigtable_instance_admin.CreateLogicalViewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_logical_view"] + + @property + def get_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.GetLogicalViewRequest], Awaitable[instance.LogicalView] + ]: + r"""Return a callable for the get logical view method over gRPC. + + Gets information about a logical view. + + Returns: + Callable[[~.GetLogicalViewRequest], + Awaitable[~.LogicalView]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_logical_view" not in self._stubs: + self._stubs["get_logical_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetLogicalView", + request_serializer=bigtable_instance_admin.GetLogicalViewRequest.serialize, + response_deserializer=instance.LogicalView.deserialize, + ) + return self._stubs["get_logical_view"] + + @property + def list_logical_views( + self, + ) -> Callable[ + [bigtable_instance_admin.ListLogicalViewsRequest], + Awaitable[bigtable_instance_admin.ListLogicalViewsResponse], + ]: + r"""Return a callable for the list logical views method over gRPC. + + Lists information about logical views in an instance. + + Returns: + Callable[[~.ListLogicalViewsRequest], + Awaitable[~.ListLogicalViewsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_logical_views" not in self._stubs: + self._stubs["list_logical_views"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListLogicalViews", + request_serializer=bigtable_instance_admin.ListLogicalViewsRequest.serialize, + response_deserializer=bigtable_instance_admin.ListLogicalViewsResponse.deserialize, + ) + return self._stubs["list_logical_views"] + + @property + def update_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateLogicalViewRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update logical view method over gRPC. + + Updates a logical view within an instance. + + Returns: + Callable[[~.UpdateLogicalViewRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_logical_view" not in self._stubs: + self._stubs["update_logical_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateLogicalView", + request_serializer=bigtable_instance_admin.UpdateLogicalViewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_logical_view"] + + @property + def delete_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.DeleteLogicalViewRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete logical view method over gRPC. + + Deletes a logical view from an instance. + + Returns: + Callable[[~.DeleteLogicalViewRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_logical_view" not in self._stubs: + self._stubs["delete_logical_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/DeleteLogicalView", + request_serializer=bigtable_instance_admin.DeleteLogicalViewRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_logical_view"] + + @property + def create_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.CreateMaterializedViewRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create materialized view method over gRPC. + + Creates a materialized view within an instance. + + Returns: + Callable[[~.CreateMaterializedViewRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_materialized_view" not in self._stubs: + self._stubs["create_materialized_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/CreateMaterializedView", + request_serializer=bigtable_instance_admin.CreateMaterializedViewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_materialized_view"] + + @property + def get_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.GetMaterializedViewRequest], + Awaitable[instance.MaterializedView], + ]: + r"""Return a callable for the get materialized view method over gRPC. + + Gets information about a materialized view. + + Returns: + Callable[[~.GetMaterializedViewRequest], + Awaitable[~.MaterializedView]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_materialized_view" not in self._stubs: + self._stubs["get_materialized_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetMaterializedView", + request_serializer=bigtable_instance_admin.GetMaterializedViewRequest.serialize, + response_deserializer=instance.MaterializedView.deserialize, + ) + return self._stubs["get_materialized_view"] + + @property + def list_materialized_views( + self, + ) -> Callable[ + [bigtable_instance_admin.ListMaterializedViewsRequest], + Awaitable[bigtable_instance_admin.ListMaterializedViewsResponse], + ]: + r"""Return a callable for the list materialized views method over gRPC. + + Lists information about materialized views in an + instance. + + Returns: + Callable[[~.ListMaterializedViewsRequest], + Awaitable[~.ListMaterializedViewsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_materialized_views" not in self._stubs: + self._stubs["list_materialized_views"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListMaterializedViews", + request_serializer=bigtable_instance_admin.ListMaterializedViewsRequest.serialize, + response_deserializer=bigtable_instance_admin.ListMaterializedViewsResponse.deserialize, + ) + return self._stubs["list_materialized_views"] + + @property + def update_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateMaterializedViewRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update materialized view method over gRPC. + + Updates a materialized view within an instance. + + Returns: + Callable[[~.UpdateMaterializedViewRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_materialized_view" not in self._stubs: + self._stubs["update_materialized_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateMaterializedView", + request_serializer=bigtable_instance_admin.UpdateMaterializedViewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_materialized_view"] + + @property + def delete_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.DeleteMaterializedViewRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete materialized view method over gRPC. + + Deletes a materialized view from an instance. + + Returns: + Callable[[~.DeleteMaterializedViewRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_materialized_view" not in self._stubs: + self._stubs["delete_materialized_view"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/DeleteMaterializedView", + request_serializer=bigtable_instance_admin.DeleteMaterializedViewRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_materialized_view"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -1137,6 +1511,56 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.create_logical_view: self._wrap_method( + self.create_logical_view, + default_timeout=None, + client_info=client_info, + ), + self.get_logical_view: self._wrap_method( + self.get_logical_view, + default_timeout=None, + client_info=client_info, + ), + self.list_logical_views: self._wrap_method( + self.list_logical_views, + default_timeout=None, + client_info=client_info, + ), + self.update_logical_view: self._wrap_method( + self.update_logical_view, + default_timeout=None, + client_info=client_info, + ), + self.delete_logical_view: self._wrap_method( + self.delete_logical_view, + default_timeout=None, + client_info=client_info, + ), + self.create_materialized_view: self._wrap_method( + self.create_materialized_view, + default_timeout=None, + client_info=client_info, + ), + self.get_materialized_view: self._wrap_method( + self.get_materialized_view, + default_timeout=None, + client_info=client_info, + ), + self.list_materialized_views: self._wrap_method( + self.list_materialized_views, + default_timeout=None, + client_info=client_info, + ), + self.update_materialized_view: self._wrap_method( + self.update_materialized_view, + default_timeout=None, + client_info=client_info, + ), + self.delete_materialized_view: self._wrap_method( + self.delete_materialized_view, + default_timeout=None, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): @@ -1145,7 +1569,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest.py b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest.py index 45f08fa64..858055974 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest.py @@ -13,9 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import logging +import json # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries @@ -48,6 +49,14 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -95,6 +104,22 @@ def post_create_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_create_logical_view(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_logical_view(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_materialized_view(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_materialized_view(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_app_profile(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -107,6 +132,14 @@ def pre_delete_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata + def pre_delete_logical_view(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_materialized_view(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + def pre_get_app_profile(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -139,6 +172,22 @@ def post_get_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_get_logical_view(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_logical_view(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_materialized_view(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_materialized_view(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_app_profiles(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -171,6 +220,22 @@ def post_list_instances(self, response): logging.log(f"Received response: {response}") return response + def pre_list_logical_views(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_logical_views(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_materialized_views(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_materialized_views(self, response): + logging.log(f"Received response: {response}") + return response + def pre_partial_update_cluster(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -227,6 +292,22 @@ def post_update_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_update_logical_view(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_logical_view(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_materialized_view(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_materialized_view(self, response): + logging.log(f"Received response: {response}") + return response + transport = BigtableInstanceAdminRestTransport(interceptor=MyCustomBigtableInstanceAdminInterceptor()) client = BigtableInstanceAdminClient(transport=transport) @@ -236,9 +317,10 @@ def post_update_instance(self, response): def pre_create_app_profile( self, request: bigtable_instance_admin.CreateAppProfileRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_instance_admin.CreateAppProfileRequest, Sequence[Tuple[str, str]] + bigtable_instance_admin.CreateAppProfileRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for create_app_profile @@ -252,17 +334,43 @@ def post_create_app_profile( ) -> instance.AppProfile: """Post-rpc interceptor for create_app_profile - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_create_app_profile_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_create_app_profile` interceptor runs + before the `post_create_app_profile_with_metadata` interceptor. """ return response + def post_create_app_profile_with_metadata( + self, + response: instance.AppProfile, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.AppProfile, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_app_profile + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_create_app_profile_with_metadata` + interceptor in new development instead of the `post_create_app_profile` interceptor. + When both interceptors are used, this `post_create_app_profile_with_metadata` interceptor runs after the + `post_create_app_profile` interceptor. The (possibly modified) response returned by + `post_create_app_profile` will be passed to + `post_create_app_profile_with_metadata`. + """ + return response, metadata + def pre_create_cluster( self, request: bigtable_instance_admin.CreateClusterRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_instance_admin.CreateClusterRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.CreateClusterRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_cluster Override in a subclass to manipulate the request or metadata @@ -275,18 +383,42 @@ def post_create_cluster( ) -> operations_pb2.Operation: """Post-rpc interceptor for create_cluster - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_create_cluster_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_create_cluster` interceptor runs + before the `post_create_cluster_with_metadata` interceptor. """ return response + def post_create_cluster_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_cluster + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_create_cluster_with_metadata` + interceptor in new development instead of the `post_create_cluster` interceptor. + When both interceptors are used, this `post_create_cluster_with_metadata` interceptor runs after the + `post_create_cluster` interceptor. The (possibly modified) response returned by + `post_create_cluster` will be passed to + `post_create_cluster_with_metadata`. + """ + return response, metadata + def pre_create_instance( self, request: bigtable_instance_admin.CreateInstanceRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_instance_admin.CreateInstanceRequest, Sequence[Tuple[str, str]] + bigtable_instance_admin.CreateInstanceRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for create_instance @@ -300,18 +432,140 @@ def post_create_instance( ) -> operations_pb2.Operation: """Post-rpc interceptor for create_instance - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_create_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_create_instance` interceptor runs + before the `post_create_instance_with_metadata` interceptor. + """ + return response + + def post_create_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_create_instance_with_metadata` + interceptor in new development instead of the `post_create_instance` interceptor. + When both interceptors are used, this `post_create_instance_with_metadata` interceptor runs after the + `post_create_instance` interceptor. The (possibly modified) response returned by + `post_create_instance` will be passed to + `post_create_instance_with_metadata`. + """ + return response, metadata + + def pre_create_logical_view( + self, + request: bigtable_instance_admin.CreateLogicalViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.CreateLogicalViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_logical_view + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_create_logical_view( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_logical_view + + DEPRECATED. Please use the `post_create_logical_view_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_create_logical_view` interceptor runs + before the `post_create_logical_view_with_metadata` interceptor. + """ + return response + + def post_create_logical_view_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_logical_view + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_create_logical_view_with_metadata` + interceptor in new development instead of the `post_create_logical_view` interceptor. + When both interceptors are used, this `post_create_logical_view_with_metadata` interceptor runs after the + `post_create_logical_view` interceptor. The (possibly modified) response returned by + `post_create_logical_view` will be passed to + `post_create_logical_view_with_metadata`. + """ + return response, metadata + + def pre_create_materialized_view( + self, + request: bigtable_instance_admin.CreateMaterializedViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.CreateMaterializedViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_materialized_view + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_create_materialized_view( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_materialized_view + + DEPRECATED. Please use the `post_create_materialized_view_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_create_materialized_view` interceptor runs + before the `post_create_materialized_view_with_metadata` interceptor. """ return response + def post_create_materialized_view_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_materialized_view + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_create_materialized_view_with_metadata` + interceptor in new development instead of the `post_create_materialized_view` interceptor. + When both interceptors are used, this `post_create_materialized_view_with_metadata` interceptor runs after the + `post_create_materialized_view` interceptor. The (possibly modified) response returned by + `post_create_materialized_view` will be passed to + `post_create_materialized_view_with_metadata`. + """ + return response, metadata + def pre_delete_app_profile( self, request: bigtable_instance_admin.DeleteAppProfileRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_instance_admin.DeleteAppProfileRequest, Sequence[Tuple[str, str]] + bigtable_instance_admin.DeleteAppProfileRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for delete_app_profile @@ -323,8 +577,11 @@ def pre_delete_app_profile( def pre_delete_cluster( self, request: bigtable_instance_admin.DeleteClusterRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_instance_admin.DeleteClusterRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.DeleteClusterRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for delete_cluster Override in a subclass to manipulate the request or metadata @@ -335,9 +592,10 @@ def pre_delete_cluster( def pre_delete_instance( self, request: bigtable_instance_admin.DeleteInstanceRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_instance_admin.DeleteInstanceRequest, Sequence[Tuple[str, str]] + bigtable_instance_admin.DeleteInstanceRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for delete_instance @@ -346,11 +604,44 @@ def pre_delete_instance( """ return request, metadata + def pre_delete_logical_view( + self, + request: bigtable_instance_admin.DeleteLogicalViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.DeleteLogicalViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_logical_view + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def pre_delete_materialized_view( + self, + request: bigtable_instance_admin.DeleteMaterializedViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.DeleteMaterializedViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_materialized_view + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + def pre_get_app_profile( self, request: bigtable_instance_admin.GetAppProfileRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_instance_admin.GetAppProfileRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.GetAppProfileRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_app_profile Override in a subclass to manipulate the request or metadata @@ -363,17 +654,43 @@ def post_get_app_profile( ) -> instance.AppProfile: """Post-rpc interceptor for get_app_profile - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_app_profile_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_get_app_profile` interceptor runs + before the `post_get_app_profile_with_metadata` interceptor. """ return response + def post_get_app_profile_with_metadata( + self, + response: instance.AppProfile, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.AppProfile, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_app_profile + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_get_app_profile_with_metadata` + interceptor in new development instead of the `post_get_app_profile` interceptor. + When both interceptors are used, this `post_get_app_profile_with_metadata` interceptor runs after the + `post_get_app_profile` interceptor. The (possibly modified) response returned by + `post_get_app_profile` will be passed to + `post_get_app_profile_with_metadata`. + """ + return response, metadata + def pre_get_cluster( self, request: bigtable_instance_admin.GetClusterRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_instance_admin.GetClusterRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.GetClusterRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_cluster Override in a subclass to manipulate the request or metadata @@ -384,17 +701,42 @@ def pre_get_cluster( def post_get_cluster(self, response: instance.Cluster) -> instance.Cluster: """Post-rpc interceptor for get_cluster - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_cluster_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_get_cluster` interceptor runs + before the `post_get_cluster_with_metadata` interceptor. """ return response + def post_get_cluster_with_metadata( + self, + response: instance.Cluster, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.Cluster, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_cluster + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_get_cluster_with_metadata` + interceptor in new development instead of the `post_get_cluster` interceptor. + When both interceptors are used, this `post_get_cluster_with_metadata` interceptor runs after the + `post_get_cluster` interceptor. The (possibly modified) response returned by + `post_get_cluster` will be passed to + `post_get_cluster_with_metadata`. + """ + return response, metadata + def pre_get_iam_policy( self, request: iam_policy_pb2.GetIamPolicyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_iam_policy Override in a subclass to manipulate the request or metadata @@ -405,17 +747,43 @@ def pre_get_iam_policy( def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for get_iam_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_iam_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_get_iam_policy` interceptor runs + before the `post_get_iam_policy_with_metadata` interceptor. """ return response + def post_get_iam_policy_with_metadata( + self, + response: policy_pb2.Policy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[policy_pb2.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_get_iam_policy_with_metadata` + interceptor in new development instead of the `post_get_iam_policy` interceptor. + When both interceptors are used, this `post_get_iam_policy_with_metadata` interceptor runs after the + `post_get_iam_policy` interceptor. The (possibly modified) response returned by + `post_get_iam_policy` will be passed to + `post_get_iam_policy_with_metadata`. + """ + return response, metadata + def pre_get_instance( self, request: bigtable_instance_admin.GetInstanceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_instance_admin.GetInstanceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.GetInstanceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_instance Override in a subclass to manipulate the request or metadata @@ -426,18 +794,140 @@ def pre_get_instance( def post_get_instance(self, response: instance.Instance) -> instance.Instance: """Post-rpc interceptor for get_instance - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_get_instance` interceptor runs + before the `post_get_instance_with_metadata` interceptor. + """ + return response + + def post_get_instance_with_metadata( + self, + response: instance.Instance, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_get_instance_with_metadata` + interceptor in new development instead of the `post_get_instance` interceptor. + When both interceptors are used, this `post_get_instance_with_metadata` interceptor runs after the + `post_get_instance` interceptor. The (possibly modified) response returned by + `post_get_instance` will be passed to + `post_get_instance_with_metadata`. + """ + return response, metadata + + def pre_get_logical_view( + self, + request: bigtable_instance_admin.GetLogicalViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.GetLogicalViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_logical_view + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_get_logical_view( + self, response: instance.LogicalView + ) -> instance.LogicalView: + """Post-rpc interceptor for get_logical_view + + DEPRECATED. Please use the `post_get_logical_view_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_get_logical_view` interceptor runs + before the `post_get_logical_view_with_metadata` interceptor. + """ + return response + + def post_get_logical_view_with_metadata( + self, + response: instance.LogicalView, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.LogicalView, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_logical_view + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_get_logical_view_with_metadata` + interceptor in new development instead of the `post_get_logical_view` interceptor. + When both interceptors are used, this `post_get_logical_view_with_metadata` interceptor runs after the + `post_get_logical_view` interceptor. The (possibly modified) response returned by + `post_get_logical_view` will be passed to + `post_get_logical_view_with_metadata`. + """ + return response, metadata + + def pre_get_materialized_view( + self, + request: bigtable_instance_admin.GetMaterializedViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.GetMaterializedViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_materialized_view + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_get_materialized_view( + self, response: instance.MaterializedView + ) -> instance.MaterializedView: + """Post-rpc interceptor for get_materialized_view + + DEPRECATED. Please use the `post_get_materialized_view_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_get_materialized_view` interceptor runs + before the `post_get_materialized_view_with_metadata` interceptor. """ return response + def post_get_materialized_view_with_metadata( + self, + response: instance.MaterializedView, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.MaterializedView, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_materialized_view + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_get_materialized_view_with_metadata` + interceptor in new development instead of the `post_get_materialized_view` interceptor. + When both interceptors are used, this `post_get_materialized_view_with_metadata` interceptor runs after the + `post_get_materialized_view` interceptor. The (possibly modified) response returned by + `post_get_materialized_view` will be passed to + `post_get_materialized_view_with_metadata`. + """ + return response, metadata + def pre_list_app_profiles( self, request: bigtable_instance_admin.ListAppProfilesRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_instance_admin.ListAppProfilesRequest, Sequence[Tuple[str, str]] + bigtable_instance_admin.ListAppProfilesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for list_app_profiles @@ -451,17 +941,46 @@ def post_list_app_profiles( ) -> bigtable_instance_admin.ListAppProfilesResponse: """Post-rpc interceptor for list_app_profiles - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_app_profiles_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_list_app_profiles` interceptor runs + before the `post_list_app_profiles_with_metadata` interceptor. """ return response + def post_list_app_profiles_with_metadata( + self, + response: bigtable_instance_admin.ListAppProfilesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListAppProfilesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_app_profiles + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_list_app_profiles_with_metadata` + interceptor in new development instead of the `post_list_app_profiles` interceptor. + When both interceptors are used, this `post_list_app_profiles_with_metadata` interceptor runs after the + `post_list_app_profiles` interceptor. The (possibly modified) response returned by + `post_list_app_profiles` will be passed to + `post_list_app_profiles_with_metadata`. + """ + return response, metadata + def pre_list_clusters( self, request: bigtable_instance_admin.ListClustersRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_instance_admin.ListClustersRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListClustersRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_clusters Override in a subclass to manipulate the request or metadata @@ -474,18 +993,45 @@ def post_list_clusters( ) -> bigtable_instance_admin.ListClustersResponse: """Post-rpc interceptor for list_clusters - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_clusters_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_list_clusters` interceptor runs + before the `post_list_clusters_with_metadata` interceptor. """ return response + def post_list_clusters_with_metadata( + self, + response: bigtable_instance_admin.ListClustersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListClustersResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_clusters + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_list_clusters_with_metadata` + interceptor in new development instead of the `post_list_clusters` interceptor. + When both interceptors are used, this `post_list_clusters_with_metadata` interceptor runs after the + `post_list_clusters` interceptor. The (possibly modified) response returned by + `post_list_clusters` will be passed to + `post_list_clusters_with_metadata`. + """ + return response, metadata + def pre_list_hot_tablets( self, request: bigtable_instance_admin.ListHotTabletsRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_instance_admin.ListHotTabletsRequest, Sequence[Tuple[str, str]] + bigtable_instance_admin.ListHotTabletsRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for list_hot_tablets @@ -499,17 +1045,46 @@ def post_list_hot_tablets( ) -> bigtable_instance_admin.ListHotTabletsResponse: """Post-rpc interceptor for list_hot_tablets - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_hot_tablets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_list_hot_tablets` interceptor runs + before the `post_list_hot_tablets_with_metadata` interceptor. """ return response + def post_list_hot_tablets_with_metadata( + self, + response: bigtable_instance_admin.ListHotTabletsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListHotTabletsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_hot_tablets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_list_hot_tablets_with_metadata` + interceptor in new development instead of the `post_list_hot_tablets` interceptor. + When both interceptors are used, this `post_list_hot_tablets_with_metadata` interceptor runs after the + `post_list_hot_tablets` interceptor. The (possibly modified) response returned by + `post_list_hot_tablets` will be passed to + `post_list_hot_tablets_with_metadata`. + """ + return response, metadata + def pre_list_instances( self, request: bigtable_instance_admin.ListInstancesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_instance_admin.ListInstancesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListInstancesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_instances Override in a subclass to manipulate the request or metadata @@ -522,23 +1097,154 @@ def post_list_instances( ) -> bigtable_instance_admin.ListInstancesResponse: """Post-rpc interceptor for list_instances - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_instances_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_list_instances` interceptor runs + before the `post_list_instances_with_metadata` interceptor. """ return response - def pre_partial_update_cluster( + def post_list_instances_with_metadata( self, - request: bigtable_instance_admin.PartialUpdateClusterRequest, - metadata: Sequence[Tuple[str, str]], + response: bigtable_instance_admin.ListInstancesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_instance_admin.PartialUpdateClusterRequest, Sequence[Tuple[str, str]] + bigtable_instance_admin.ListInstancesResponse, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for partial_update_cluster + """Post-rpc interceptor for list_instances - Override in a subclass to manipulate the request or metadata - before they are sent to the BigtableInstanceAdmin server. + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_list_instances_with_metadata` + interceptor in new development instead of the `post_list_instances` interceptor. + When both interceptors are used, this `post_list_instances_with_metadata` interceptor runs after the + `post_list_instances` interceptor. The (possibly modified) response returned by + `post_list_instances` will be passed to + `post_list_instances_with_metadata`. + """ + return response, metadata + + def pre_list_logical_views( + self, + request: bigtable_instance_admin.ListLogicalViewsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListLogicalViewsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_logical_views + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_list_logical_views( + self, response: bigtable_instance_admin.ListLogicalViewsResponse + ) -> bigtable_instance_admin.ListLogicalViewsResponse: + """Post-rpc interceptor for list_logical_views + + DEPRECATED. Please use the `post_list_logical_views_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_list_logical_views` interceptor runs + before the `post_list_logical_views_with_metadata` interceptor. + """ + return response + + def post_list_logical_views_with_metadata( + self, + response: bigtable_instance_admin.ListLogicalViewsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListLogicalViewsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_logical_views + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_list_logical_views_with_metadata` + interceptor in new development instead of the `post_list_logical_views` interceptor. + When both interceptors are used, this `post_list_logical_views_with_metadata` interceptor runs after the + `post_list_logical_views` interceptor. The (possibly modified) response returned by + `post_list_logical_views` will be passed to + `post_list_logical_views_with_metadata`. + """ + return response, metadata + + def pre_list_materialized_views( + self, + request: bigtable_instance_admin.ListMaterializedViewsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListMaterializedViewsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_materialized_views + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_list_materialized_views( + self, response: bigtable_instance_admin.ListMaterializedViewsResponse + ) -> bigtable_instance_admin.ListMaterializedViewsResponse: + """Post-rpc interceptor for list_materialized_views + + DEPRECATED. Please use the `post_list_materialized_views_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_list_materialized_views` interceptor runs + before the `post_list_materialized_views_with_metadata` interceptor. + """ + return response + + def post_list_materialized_views_with_metadata( + self, + response: bigtable_instance_admin.ListMaterializedViewsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListMaterializedViewsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_materialized_views + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_list_materialized_views_with_metadata` + interceptor in new development instead of the `post_list_materialized_views` interceptor. + When both interceptors are used, this `post_list_materialized_views_with_metadata` interceptor runs after the + `post_list_materialized_views` interceptor. The (possibly modified) response returned by + `post_list_materialized_views` will be passed to + `post_list_materialized_views_with_metadata`. + """ + return response, metadata + + def pre_partial_update_cluster( + self, + request: bigtable_instance_admin.PartialUpdateClusterRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.PartialUpdateClusterRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for partial_update_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. """ return request, metadata @@ -547,18 +1253,42 @@ def post_partial_update_cluster( ) -> operations_pb2.Operation: """Post-rpc interceptor for partial_update_cluster - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_partial_update_cluster_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_partial_update_cluster` interceptor runs + before the `post_partial_update_cluster_with_metadata` interceptor. """ return response + def post_partial_update_cluster_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for partial_update_cluster + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_partial_update_cluster_with_metadata` + interceptor in new development instead of the `post_partial_update_cluster` interceptor. + When both interceptors are used, this `post_partial_update_cluster_with_metadata` interceptor runs after the + `post_partial_update_cluster` interceptor. The (possibly modified) response returned by + `post_partial_update_cluster` will be passed to + `post_partial_update_cluster_with_metadata`. + """ + return response, metadata + def pre_partial_update_instance( self, request: bigtable_instance_admin.PartialUpdateInstanceRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_instance_admin.PartialUpdateInstanceRequest, Sequence[Tuple[str, str]] + bigtable_instance_admin.PartialUpdateInstanceRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for partial_update_instance @@ -572,17 +1302,42 @@ def post_partial_update_instance( ) -> operations_pb2.Operation: """Post-rpc interceptor for partial_update_instance - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_partial_update_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_partial_update_instance` interceptor runs + before the `post_partial_update_instance_with_metadata` interceptor. """ return response + def post_partial_update_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for partial_update_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_partial_update_instance_with_metadata` + interceptor in new development instead of the `post_partial_update_instance` interceptor. + When both interceptors are used, this `post_partial_update_instance_with_metadata` interceptor runs after the + `post_partial_update_instance` interceptor. The (possibly modified) response returned by + `post_partial_update_instance` will be passed to + `post_partial_update_instance_with_metadata`. + """ + return response, metadata + def pre_set_iam_policy( self, request: iam_policy_pb2.SetIamPolicyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for set_iam_policy Override in a subclass to manipulate the request or metadata @@ -593,17 +1348,43 @@ def pre_set_iam_policy( def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for set_iam_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_set_iam_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_set_iam_policy` interceptor runs + before the `post_set_iam_policy_with_metadata` interceptor. """ return response + def post_set_iam_policy_with_metadata( + self, + response: policy_pb2.Policy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[policy_pb2.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_set_iam_policy_with_metadata` + interceptor in new development instead of the `post_set_iam_policy` interceptor. + When both interceptors are used, this `post_set_iam_policy_with_metadata` interceptor runs after the + `post_set_iam_policy` interceptor. The (possibly modified) response returned by + `post_set_iam_policy` will be passed to + `post_set_iam_policy_with_metadata`. + """ + return response, metadata + def pre_test_iam_permissions( self, request: iam_policy_pb2.TestIamPermissionsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for test_iam_permissions Override in a subclass to manipulate the request or metadata @@ -616,18 +1397,45 @@ def post_test_iam_permissions( ) -> iam_policy_pb2.TestIamPermissionsResponse: """Post-rpc interceptor for test_iam_permissions - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_test_iam_permissions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_test_iam_permissions` interceptor runs + before the `post_test_iam_permissions_with_metadata` interceptor. """ return response + def post_test_iam_permissions_with_metadata( + self, + response: iam_policy_pb2.TestIamPermissionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_test_iam_permissions_with_metadata` + interceptor in new development instead of the `post_test_iam_permissions` interceptor. + When both interceptors are used, this `post_test_iam_permissions_with_metadata` interceptor runs after the + `post_test_iam_permissions` interceptor. The (possibly modified) response returned by + `post_test_iam_permissions` will be passed to + `post_test_iam_permissions_with_metadata`. + """ + return response, metadata + def pre_update_app_profile( self, request: bigtable_instance_admin.UpdateAppProfileRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_instance_admin.UpdateAppProfileRequest, Sequence[Tuple[str, str]] + bigtable_instance_admin.UpdateAppProfileRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_app_profile @@ -641,15 +1449,40 @@ def post_update_app_profile( ) -> operations_pb2.Operation: """Post-rpc interceptor for update_app_profile - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_update_app_profile_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_update_app_profile` interceptor runs + before the `post_update_app_profile_with_metadata` interceptor. """ return response + def post_update_app_profile_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_app_profile + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_update_app_profile_with_metadata` + interceptor in new development instead of the `post_update_app_profile` interceptor. + When both interceptors are used, this `post_update_app_profile_with_metadata` interceptor runs after the + `post_update_app_profile` interceptor. The (possibly modified) response returned by + `post_update_app_profile` will be passed to + `post_update_app_profile_with_metadata`. + """ + return response, metadata + def pre_update_cluster( - self, request: instance.Cluster, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[instance.Cluster, Sequence[Tuple[str, str]]]: + self, + request: instance.Cluster, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.Cluster, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_cluster Override in a subclass to manipulate the request or metadata @@ -662,15 +1495,40 @@ def post_update_cluster( ) -> operations_pb2.Operation: """Post-rpc interceptor for update_cluster - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_update_cluster_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_update_cluster` interceptor runs + before the `post_update_cluster_with_metadata` interceptor. """ return response + def post_update_cluster_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_cluster + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_update_cluster_with_metadata` + interceptor in new development instead of the `post_update_cluster` interceptor. + When both interceptors are used, this `post_update_cluster_with_metadata` interceptor runs after the + `post_update_cluster` interceptor. The (possibly modified) response returned by + `post_update_cluster` will be passed to + `post_update_cluster_with_metadata`. + """ + return response, metadata + def pre_update_instance( - self, request: instance.Instance, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[instance.Instance, Sequence[Tuple[str, str]]]: + self, + request: instance.Instance, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_instance Override in a subclass to manipulate the request or metadata @@ -681,12 +1539,133 @@ def pre_update_instance( def post_update_instance(self, response: instance.Instance) -> instance.Instance: """Post-rpc interceptor for update_instance - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_update_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_update_instance` interceptor runs + before the `post_update_instance_with_metadata` interceptor. + """ + return response + + def post_update_instance_with_metadata( + self, + response: instance.Instance, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_update_instance_with_metadata` + interceptor in new development instead of the `post_update_instance` interceptor. + When both interceptors are used, this `post_update_instance_with_metadata` interceptor runs after the + `post_update_instance` interceptor. The (possibly modified) response returned by + `post_update_instance` will be passed to + `post_update_instance_with_metadata`. + """ + return response, metadata + + def pre_update_logical_view( + self, + request: bigtable_instance_admin.UpdateLogicalViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.UpdateLogicalViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_logical_view + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_update_logical_view( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_logical_view + + DEPRECATED. Please use the `post_update_logical_view_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_update_logical_view` interceptor runs + before the `post_update_logical_view_with_metadata` interceptor. + """ + return response + + def post_update_logical_view_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_logical_view + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_update_logical_view_with_metadata` + interceptor in new development instead of the `post_update_logical_view` interceptor. + When both interceptors are used, this `post_update_logical_view_with_metadata` interceptor runs after the + `post_update_logical_view` interceptor. The (possibly modified) response returned by + `post_update_logical_view` will be passed to + `post_update_logical_view_with_metadata`. + """ + return response, metadata + + def pre_update_materialized_view( + self, + request: bigtable_instance_admin.UpdateMaterializedViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.UpdateMaterializedViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_materialized_view + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_update_materialized_view( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_materialized_view + + DEPRECATED. Please use the `post_update_materialized_view_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableInstanceAdmin server but before - it is returned to user code. + it is returned to user code. This `post_update_materialized_view` interceptor runs + before the `post_update_materialized_view_with_metadata` interceptor. """ return response + def post_update_materialized_view_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_materialized_view + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_update_materialized_view_with_metadata` + interceptor in new development instead of the `post_update_materialized_view` interceptor. + When both interceptors are used, this `post_update_materialized_view_with_metadata` interceptor runs after the + `post_update_materialized_view` interceptor. The (possibly modified) response returned by + `post_update_materialized_view` will be passed to + `post_update_materialized_view_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class BigtableInstanceAdminRestStub: @@ -866,7 +1845,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.AppProfile: r"""Call the create app profile method over HTTP. @@ -877,8 +1856,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.instance.AppProfile: @@ -891,6 +1872,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseCreateAppProfile._get_http_options() ) + request, metadata = self._interceptor.pre_create_app_profile( request, metadata ) @@ -907,6 +1889,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.CreateAppProfile", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "CreateAppProfile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableInstanceAdminRestTransport._CreateAppProfile._get_response( @@ -930,7 +1939,33 @@ def __call__( pb_resp = instance.AppProfile.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_app_profile(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_app_profile_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.AppProfile.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.create_app_profile", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "CreateAppProfile", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CreateCluster( @@ -969,7 +2004,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the create cluster method over HTTP. @@ -980,8 +2015,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -994,6 +2031,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseCreateCluster._get_http_options() ) + request, metadata = self._interceptor.pre_create_cluster(request, metadata) transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseCreateCluster._get_transcoded_request( http_options, request @@ -1008,6 +2046,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.CreateCluster", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "CreateCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableInstanceAdminRestTransport._CreateCluster._get_response( self._host, @@ -1027,7 +2092,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_cluster(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_cluster_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.create_cluster", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "CreateCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CreateInstance( @@ -1066,7 +2157,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the create instance method over HTTP. @@ -1077,8 +2168,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1091,6 +2184,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseCreateInstance._get_http_options() ) + request, metadata = self._interceptor.pre_create_instance(request, metadata) transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseCreateInstance._get_transcoded_request( http_options, request @@ -1105,6 +2199,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.CreateInstance", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "CreateInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableInstanceAdminRestTransport._CreateInstance._get_response( self._host, @@ -1124,15 +2245,41 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.create_instance", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "CreateInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _DeleteAppProfile( - _BaseBigtableInstanceAdminRestTransport._BaseDeleteAppProfile, + class _CreateLogicalView( + _BaseBigtableInstanceAdminRestTransport._BaseCreateLogicalView, BigtableInstanceAdminRestStub, ): def __hash__(self): - return hash("BigtableInstanceAdminRestTransport.DeleteAppProfile") + return hash("BigtableInstanceAdminRestTransport.CreateLogicalView") @staticmethod def _get_response( @@ -1153,54 +2300,97 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: bigtable_instance_admin.DeleteAppProfileRequest, + request: bigtable_instance_admin.CreateLogicalViewRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ): - r"""Call the delete app profile method over HTTP. + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create logical view method over HTTP. Args: - request (~.bigtable_instance_admin.DeleteAppProfileRequest): + request (~.bigtable_instance_admin.CreateLogicalViewRequest): The request object. Request message for - BigtableInstanceAdmin.DeleteAppProfile. + BigtableInstanceAdmin.CreateLogicalView. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + """ http_options = ( - _BaseBigtableInstanceAdminRestTransport._BaseDeleteAppProfile._get_http_options() + _BaseBigtableInstanceAdminRestTransport._BaseCreateLogicalView._get_http_options() ) - request, metadata = self._interceptor.pre_delete_app_profile( + + request, metadata = self._interceptor.pre_create_logical_view( request, metadata ) - transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseDeleteAppProfile._get_transcoded_request( + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseCreateLogicalView._get_transcoded_request( http_options, request ) + body = _BaseBigtableInstanceAdminRestTransport._BaseCreateLogicalView._get_request_body_json( + transcoded_request + ) + # Jsonify the query params - query_params = _BaseBigtableInstanceAdminRestTransport._BaseDeleteAppProfile._get_query_params_json( + query_params = _BaseBigtableInstanceAdminRestTransport._BaseCreateLogicalView._get_query_params_json( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.CreateLogicalView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "CreateLogicalView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( - BigtableInstanceAdminRestTransport._DeleteAppProfile._get_response( + BigtableInstanceAdminRestTransport._CreateLogicalView._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) ) @@ -1209,12 +2399,44 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteCluster( - _BaseBigtableInstanceAdminRestTransport._BaseDeleteCluster, + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_logical_view(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_logical_view_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.create_logical_view", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "CreateLogicalView", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateMaterializedView( + _BaseBigtableInstanceAdminRestTransport._BaseCreateMaterializedView, BigtableInstanceAdminRestStub, ): def __hash__(self): - return hash("BigtableInstanceAdminRestTransport.DeleteCluster") + return hash("BigtableInstanceAdminRestTransport.CreateMaterializedView") @staticmethod def _get_response( @@ -1235,51 +2457,96 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: bigtable_instance_admin.DeleteClusterRequest, + request: bigtable_instance_admin.CreateMaterializedViewRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ): - r"""Call the delete cluster method over HTTP. + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create materialized view method over HTTP. Args: - request (~.bigtable_instance_admin.DeleteClusterRequest): + request (~.bigtable_instance_admin.CreateMaterializedViewRequest): The request object. Request message for - BigtableInstanceAdmin.DeleteCluster. + BigtableInstanceAdmin.CreateMaterializedView. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + """ http_options = ( - _BaseBigtableInstanceAdminRestTransport._BaseDeleteCluster._get_http_options() + _BaseBigtableInstanceAdminRestTransport._BaseCreateMaterializedView._get_http_options() ) - request, metadata = self._interceptor.pre_delete_cluster(request, metadata) - transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseDeleteCluster._get_transcoded_request( + + request, metadata = self._interceptor.pre_create_materialized_view( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseCreateMaterializedView._get_transcoded_request( http_options, request ) + body = _BaseBigtableInstanceAdminRestTransport._BaseCreateMaterializedView._get_request_body_json( + transcoded_request + ) + # Jsonify the query params - query_params = _BaseBigtableInstanceAdminRestTransport._BaseDeleteCluster._get_query_params_json( + query_params = _BaseBigtableInstanceAdminRestTransport._BaseCreateMaterializedView._get_query_params_json( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.CreateMaterializedView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "CreateMaterializedView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request - response = BigtableInstanceAdminRestTransport._DeleteCluster._get_response( + response = BigtableInstanceAdminRestTransport._CreateMaterializedView._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1287,12 +2554,484 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteInstance( - _BaseBigtableInstanceAdminRestTransport._BaseDeleteInstance, + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_materialized_view(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_materialized_view_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.create_materialized_view", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "CreateMaterializedView", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAppProfile( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteAppProfile, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.DeleteAppProfile") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.DeleteAppProfileRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete app profile method over HTTP. + + Args: + request (~.bigtable_instance_admin.DeleteAppProfileRequest): + The request object. Request message for + BigtableInstanceAdmin.DeleteAppProfile. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteAppProfile._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_app_profile( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseDeleteAppProfile._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBigtableInstanceAdminRestTransport._BaseDeleteAppProfile._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.DeleteAppProfile", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "DeleteAppProfile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BigtableInstanceAdminRestTransport._DeleteAppProfile._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteCluster( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteCluster, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.DeleteCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.DeleteClusterRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete cluster method over HTTP. + + Args: + request (~.bigtable_instance_admin.DeleteClusterRequest): + The request object. Request message for + BigtableInstanceAdmin.DeleteCluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteCluster._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_cluster(request, metadata) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseDeleteCluster._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBigtableInstanceAdminRestTransport._BaseDeleteCluster._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.DeleteCluster", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "DeleteCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BigtableInstanceAdminRestTransport._DeleteCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteInstance( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteInstance, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.DeleteInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.DeleteInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete instance method over HTTP. + + Args: + request (~.bigtable_instance_admin.DeleteInstanceRequest): + The request object. Request message for + BigtableInstanceAdmin.DeleteInstance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_instance(request, metadata) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBigtableInstanceAdminRestTransport._BaseDeleteInstance._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.DeleteInstance", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "DeleteInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BigtableInstanceAdminRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteLogicalView( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteLogicalView, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.DeleteLogicalView") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.DeleteLogicalViewRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete logical view method over HTTP. + + Args: + request (~.bigtable_instance_admin.DeleteLogicalViewRequest): + The request object. Request message for + BigtableInstanceAdmin.DeleteLogicalView. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteLogicalView._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_logical_view( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseDeleteLogicalView._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBigtableInstanceAdminRestTransport._BaseDeleteLogicalView._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.DeleteLogicalView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "DeleteLogicalView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BigtableInstanceAdminRestTransport._DeleteLogicalView._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteMaterializedView( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteMaterializedView, BigtableInstanceAdminRestStub, ): def __hash__(self): - return hash("BigtableInstanceAdminRestTransport.DeleteInstance") + return hash("BigtableInstanceAdminRestTransport.DeleteMaterializedView") @staticmethod def _get_response( @@ -1318,40 +3057,72 @@ def _get_response( def __call__( self, - request: bigtable_instance_admin.DeleteInstanceRequest, + request: bigtable_instance_admin.DeleteMaterializedViewRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): - r"""Call the delete instance method over HTTP. + r"""Call the delete materialized view method over HTTP. Args: - request (~.bigtable_instance_admin.DeleteInstanceRequest): + request (~.bigtable_instance_admin.DeleteMaterializedViewRequest): The request object. Request message for - BigtableInstanceAdmin.DeleteInstance. + BigtableInstanceAdmin.DeleteMaterializedView. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ http_options = ( - _BaseBigtableInstanceAdminRestTransport._BaseDeleteInstance._get_http_options() + _BaseBigtableInstanceAdminRestTransport._BaseDeleteMaterializedView._get_http_options() ) - request, metadata = self._interceptor.pre_delete_instance(request, metadata) - transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseDeleteInstance._get_transcoded_request( + + request, metadata = self._interceptor.pre_delete_materialized_view( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseDeleteMaterializedView._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseBigtableInstanceAdminRestTransport._BaseDeleteInstance._get_query_params_json( + query_params = _BaseBigtableInstanceAdminRestTransport._BaseDeleteMaterializedView._get_query_params_json( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.DeleteMaterializedView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "DeleteMaterializedView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request - response = BigtableInstanceAdminRestTransport._DeleteInstance._get_response( + response = BigtableInstanceAdminRestTransport._DeleteMaterializedView._get_response( self._host, metadata, query_params, @@ -1400,7 +3171,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.AppProfile: r"""Call the get app profile method over HTTP. @@ -1411,8 +3182,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.instance.AppProfile: @@ -1425,6 +3198,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseGetAppProfile._get_http_options() ) + request, metadata = self._interceptor.pre_get_app_profile(request, metadata) transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseGetAppProfile._get_transcoded_request( http_options, request @@ -1435,6 +3209,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.GetAppProfile", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetAppProfile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableInstanceAdminRestTransport._GetAppProfile._get_response( self._host, @@ -1455,7 +3256,33 @@ def __call__( pb_resp = instance.AppProfile.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_app_profile(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_app_profile_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.AppProfile.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.get_app_profile", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetAppProfile", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetCluster( @@ -1493,7 +3320,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> instance.Cluster: r"""Call the get cluster method over HTTP. @@ -1504,8 +3331,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.instance.Cluster: @@ -1519,6 +3348,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseGetCluster._get_http_options() ) + request, metadata = self._interceptor.pre_get_cluster(request, metadata) transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseGetCluster._get_transcoded_request( http_options, request @@ -1529,6 +3359,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.GetCluster", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableInstanceAdminRestTransport._GetCluster._get_response( self._host, @@ -1549,7 +3406,33 @@ def __call__( pb_resp = instance.Cluster.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_cluster(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_cluster_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.Cluster.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.get_cluster", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetIamPolicy( @@ -1588,7 +3471,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Call the get iam policy method over HTTP. @@ -1598,8 +3481,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.policy_pb2.Policy: @@ -1684,6 +3569,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseGetIamPolicy._get_http_options() ) + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseGetIamPolicy._get_transcoded_request( http_options, request @@ -1698,15 +3584,344 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.GetIamPolicy", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BigtableInstanceAdminRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_iam_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.get_iam_policy", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetIamPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetInstance( + _BaseBigtableInstanceAdminRestTransport._BaseGetInstance, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.GetInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.GetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.bigtable_instance_admin.GetInstanceRequest): + The request object. Request message for + BigtableInstanceAdmin.GetInstance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.instance.Instance: + A collection of Bigtable + [Tables][google.bigtable.admin.v2.Table] and the + resources that serve them. All tables in an instance are + served from all + [Clusters][google.bigtable.admin.v2.Cluster] in the + instance. + + """ + + http_options = ( + _BaseBigtableInstanceAdminRestTransport._BaseGetInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_instance(request, metadata) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBigtableInstanceAdminRestTransport._BaseGetInstance._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.GetInstance", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BigtableInstanceAdminRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = instance.Instance() + pb_resp = instance.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.Instance.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.get_instance", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetLogicalView( + _BaseBigtableInstanceAdminRestTransport._BaseGetLogicalView, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.GetLogicalView") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.GetLogicalViewRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.LogicalView: + r"""Call the get logical view method over HTTP. + + Args: + request (~.bigtable_instance_admin.GetLogicalViewRequest): + The request object. Request message for + BigtableInstanceAdmin.GetLogicalView. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.instance.LogicalView: + A SQL logical view object that can be + referenced in SQL queries. + + """ + + http_options = ( + _BaseBigtableInstanceAdminRestTransport._BaseGetLogicalView._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_logical_view( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseGetLogicalView._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBigtableInstanceAdminRestTransport._BaseGetLogicalView._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.GetLogicalView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetLogicalView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request - response = BigtableInstanceAdminRestTransport._GetIamPolicy._get_response( + response = BigtableInstanceAdminRestTransport._GetLogicalView._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1715,19 +3930,45 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = policy_pb2.Policy() - pb_resp = resp + resp = instance.LogicalView() + pb_resp = instance.LogicalView.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) + + resp = self._interceptor.post_get_logical_view(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_logical_view_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.LogicalView.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.get_logical_view", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetLogicalView", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _GetInstance( - _BaseBigtableInstanceAdminRestTransport._BaseGetInstance, + class _GetMaterializedView( + _BaseBigtableInstanceAdminRestTransport._BaseGetMaterializedView, BigtableInstanceAdminRestStub, ): def __hash__(self): - return hash("BigtableInstanceAdminRestTransport.GetInstance") + return hash("BigtableInstanceAdminRestTransport.GetMaterializedView") @staticmethod def _get_response( @@ -1753,56 +3994,86 @@ def _get_response( def __call__( self, - request: bigtable_instance_admin.GetInstanceRequest, + request: bigtable_instance_admin.GetMaterializedViewRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> instance.Instance: - r"""Call the get instance method over HTTP. + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.MaterializedView: + r"""Call the get materialized view method over HTTP. Args: - request (~.bigtable_instance_admin.GetInstanceRequest): + request (~.bigtable_instance_admin.GetMaterializedViewRequest): The request object. Request message for - BigtableInstanceAdmin.GetInstance. + BigtableInstanceAdmin.GetMaterializedView. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - ~.instance.Instance: - A collection of Bigtable - [Tables][google.bigtable.admin.v2.Table] and the - resources that serve them. All tables in an instance are - served from all - [Clusters][google.bigtable.admin.v2.Cluster] in the - instance. + ~.instance.MaterializedView: + A materialized view object that can + be referenced in SQL queries. """ http_options = ( - _BaseBigtableInstanceAdminRestTransport._BaseGetInstance._get_http_options() + _BaseBigtableInstanceAdminRestTransport._BaseGetMaterializedView._get_http_options() ) - request, metadata = self._interceptor.pre_get_instance(request, metadata) - transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseGetInstance._get_transcoded_request( + + request, metadata = self._interceptor.pre_get_materialized_view( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseGetMaterializedView._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseBigtableInstanceAdminRestTransport._BaseGetInstance._get_query_params_json( + query_params = _BaseBigtableInstanceAdminRestTransport._BaseGetMaterializedView._get_query_params_json( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.GetMaterializedView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetMaterializedView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request - response = BigtableInstanceAdminRestTransport._GetInstance._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + BigtableInstanceAdminRestTransport._GetMaterializedView._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1811,11 +4082,37 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = instance.Instance() - pb_resp = instance.Instance.pb(resp) + resp = instance.MaterializedView() + pb_resp = instance.MaterializedView.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_instance(resp) + + resp = self._interceptor.post_get_materialized_view(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_materialized_view_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.MaterializedView.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.get_materialized_view", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetMaterializedView", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListAppProfiles( @@ -1853,7 +4150,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_instance_admin.ListAppProfilesResponse: r"""Call the list app profiles method over HTTP. @@ -1864,8 +4161,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable_instance_admin.ListAppProfilesResponse: @@ -1877,6 +4176,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseListAppProfiles._get_http_options() ) + request, metadata = self._interceptor.pre_list_app_profiles( request, metadata ) @@ -1889,6 +4189,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.ListAppProfiles", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListAppProfiles", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableInstanceAdminRestTransport._ListAppProfiles._get_response( @@ -1911,7 +4238,37 @@ def __call__( pb_resp = bigtable_instance_admin.ListAppProfilesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_app_profiles(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_app_profiles_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_instance_admin.ListAppProfilesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.list_app_profiles", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListAppProfiles", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListClusters( @@ -1949,7 +4306,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_instance_admin.ListClustersResponse: r"""Call the list clusters method over HTTP. @@ -1960,8 +4317,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable_instance_admin.ListClustersResponse: @@ -1973,6 +4332,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseListClusters._get_http_options() ) + request, metadata = self._interceptor.pre_list_clusters(request, metadata) transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseListClusters._get_transcoded_request( http_options, request @@ -1983,6 +4343,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.ListClusters", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListClusters", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableInstanceAdminRestTransport._ListClusters._get_response( self._host, @@ -2003,7 +4390,35 @@ def __call__( pb_resp = bigtable_instance_admin.ListClustersResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_clusters(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_clusters_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_instance_admin.ListClustersResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.list_clusters", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListClusters", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListHotTablets( @@ -2041,7 +4456,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_instance_admin.ListHotTabletsResponse: r"""Call the list hot tablets method over HTTP. @@ -2052,8 +4467,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable_instance_admin.ListHotTabletsResponse: @@ -2065,6 +4482,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseListHotTablets._get_http_options() ) + request, metadata = self._interceptor.pre_list_hot_tablets( request, metadata ) @@ -2077,6 +4495,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.ListHotTablets", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListHotTablets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableInstanceAdminRestTransport._ListHotTablets._get_response( self._host, @@ -2097,7 +4542,35 @@ def __call__( pb_resp = bigtable_instance_admin.ListHotTabletsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_hot_tablets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_hot_tablets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_instance_admin.ListHotTabletsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.list_hot_tablets", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListHotTablets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListInstances( @@ -2135,7 +4608,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_instance_admin.ListInstancesResponse: r"""Call the list instances method over HTTP. @@ -2146,8 +4619,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable_instance_admin.ListInstancesResponse: @@ -2159,6 +4634,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseListInstances._get_http_options() ) + request, metadata = self._interceptor.pre_list_instances(request, metadata) transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseListInstances._get_transcoded_request( http_options, request @@ -2169,6 +4645,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.ListInstances", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListInstances", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableInstanceAdminRestTransport._ListInstances._get_response( self._host, @@ -2185,11 +4688,351 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = bigtable_instance_admin.ListInstancesResponse() - pb_resp = bigtable_instance_admin.ListInstancesResponse.pb(resp) + resp = bigtable_instance_admin.ListInstancesResponse() + pb_resp = bigtable_instance_admin.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_instances(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_instances_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_instance_admin.ListInstancesResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.list_instances", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListInstances", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListLogicalViews( + _BaseBigtableInstanceAdminRestTransport._BaseListLogicalViews, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.ListLogicalViews") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.ListLogicalViewsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> bigtable_instance_admin.ListLogicalViewsResponse: + r"""Call the list logical views method over HTTP. + + Args: + request (~.bigtable_instance_admin.ListLogicalViewsRequest): + The request object. Request message for + BigtableInstanceAdmin.ListLogicalViews. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.bigtable_instance_admin.ListLogicalViewsResponse: + Response message for + BigtableInstanceAdmin.ListLogicalViews. + + """ + + http_options = ( + _BaseBigtableInstanceAdminRestTransport._BaseListLogicalViews._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_logical_views( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseListLogicalViews._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBigtableInstanceAdminRestTransport._BaseListLogicalViews._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.ListLogicalViews", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListLogicalViews", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BigtableInstanceAdminRestTransport._ListLogicalViews._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigtable_instance_admin.ListLogicalViewsResponse() + pb_resp = bigtable_instance_admin.ListLogicalViewsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_logical_views(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_logical_views_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_instance_admin.ListLogicalViewsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.list_logical_views", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListLogicalViews", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListMaterializedViews( + _BaseBigtableInstanceAdminRestTransport._BaseListMaterializedViews, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.ListMaterializedViews") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.ListMaterializedViewsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> bigtable_instance_admin.ListMaterializedViewsResponse: + r"""Call the list materialized views method over HTTP. + + Args: + request (~.bigtable_instance_admin.ListMaterializedViewsRequest): + The request object. Request message for + BigtableInstanceAdmin.ListMaterializedViews. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.bigtable_instance_admin.ListMaterializedViewsResponse: + Response message for + BigtableInstanceAdmin.ListMaterializedViews. + + """ + + http_options = ( + _BaseBigtableInstanceAdminRestTransport._BaseListMaterializedViews._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_materialized_views( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseListMaterializedViews._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBigtableInstanceAdminRestTransport._BaseListMaterializedViews._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.ListMaterializedViews", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListMaterializedViews", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BigtableInstanceAdminRestTransport._ListMaterializedViews._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigtable_instance_admin.ListMaterializedViewsResponse() + pb_resp = bigtable_instance_admin.ListMaterializedViewsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_instances(resp) + + resp = self._interceptor.post_list_materialized_views(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_materialized_views_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_instance_admin.ListMaterializedViewsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.list_materialized_views", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListMaterializedViews", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _PartialUpdateCluster( @@ -2228,7 +5071,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the partial update cluster method over HTTP. @@ -2239,8 +5082,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -2253,6 +5098,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BasePartialUpdateCluster._get_http_options() ) + request, metadata = self._interceptor.pre_partial_update_cluster( request, metadata ) @@ -2269,6 +5115,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.PartialUpdateCluster", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "PartialUpdateCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableInstanceAdminRestTransport._PartialUpdateCluster._get_response( @@ -2290,7 +5163,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_partial_update_cluster(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_partial_update_cluster_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.partial_update_cluster", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "PartialUpdateCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _PartialUpdateInstance( @@ -2329,7 +5228,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the partial update instance method over HTTP. @@ -2340,8 +5239,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -2354,6 +5255,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BasePartialUpdateInstance._get_http_options() ) + request, metadata = self._interceptor.pre_partial_update_instance( request, metadata ) @@ -2370,6 +5272,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.PartialUpdateInstance", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "PartialUpdateInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableInstanceAdminRestTransport._PartialUpdateInstance._get_response( @@ -2391,7 +5320,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_partial_update_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_partial_update_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.partial_update_instance", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "PartialUpdateInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _SetIamPolicy( @@ -2430,7 +5385,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Call the set iam policy method over HTTP. @@ -2440,8 +5395,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.policy_pb2.Policy: @@ -2526,6 +5483,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseSetIamPolicy._get_http_options() ) + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseSetIamPolicy._get_transcoded_request( http_options, request @@ -2540,6 +5498,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.SetIamPolicy", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableInstanceAdminRestTransport._SetIamPolicy._get_response( self._host, @@ -2561,7 +5546,33 @@ def __call__( pb_resp = resp json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_set_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.set_iam_policy", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "SetIamPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _TestIamPermissions( @@ -2600,7 +5611,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Call the test iam permissions method over HTTP. @@ -2610,8 +5621,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.iam_policy_pb2.TestIamPermissionsResponse: @@ -2621,6 +5634,7 @@ def __call__( http_options = ( _BaseBigtableInstanceAdminRestTransport._BaseTestIamPermissions._get_http_options() ) + request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) @@ -2637,6 +5651,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.TestIamPermissions", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableInstanceAdminRestTransport._TestIamPermissions._get_response( @@ -2656,19 +5697,357 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_test_iam_permissions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_test_iam_permissions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.test_iam_permissions", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "TestIamPermissions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAppProfile( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateAppProfile, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.UpdateAppProfile") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.UpdateAppProfileRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update app profile method over HTTP. + + Args: + request (~.bigtable_instance_admin.UpdateAppProfileRequest): + The request object. Request message for + BigtableInstanceAdmin.UpdateAppProfile. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateAppProfile._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_app_profile( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseUpdateAppProfile._get_transcoded_request( + http_options, request + ) + + body = _BaseBigtableInstanceAdminRestTransport._BaseUpdateAppProfile._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseBigtableInstanceAdminRestTransport._BaseUpdateAppProfile._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.UpdateAppProfile", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateAppProfile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BigtableInstanceAdminRestTransport._UpdateAppProfile._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_app_profile(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_app_profile_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.update_app_profile", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateAppProfile", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateCluster( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateCluster, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.UpdateCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: instance.Cluster, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update cluster method over HTTP. + + Args: + request (~.instance.Cluster): + The request object. A resizable group of nodes in a particular cloud + location, capable of serving all + [Tables][google.bigtable.admin.v2.Table] in the parent + [Instance][google.bigtable.admin.v2.Instance]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateCluster._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_cluster(request, metadata) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseUpdateCluster._get_transcoded_request( + http_options, request + ) + + body = _BaseBigtableInstanceAdminRestTransport._BaseUpdateCluster._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseBigtableInstanceAdminRestTransport._BaseUpdateCluster._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.UpdateCluster", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BigtableInstanceAdminRestTransport._UpdateCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) + resp = self._interceptor.post_update_cluster(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_cluster_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.update_cluster", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _UpdateAppProfile( - _BaseBigtableInstanceAdminRestTransport._BaseUpdateAppProfile, + class _UpdateInstance( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateInstance, BigtableInstanceAdminRestStub, ): def __hash__(self): - return hash("BigtableInstanceAdminRestTransport.UpdateAppProfile") + return hash("BigtableInstanceAdminRestTransport.UpdateInstance") @staticmethod def _get_response( @@ -2695,62 +6074,95 @@ def _get_response( def __call__( self, - request: bigtable_instance_admin.UpdateAppProfileRequest, + request: instance.Instance, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Call the update app profile method over HTTP. + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.Instance: + r"""Call the update instance method over HTTP. Args: - request (~.bigtable_instance_admin.UpdateAppProfileRequest): - The request object. Request message for - BigtableInstanceAdmin.UpdateAppProfile. + request (~.instance.Instance): + The request object. A collection of Bigtable + [Tables][google.bigtable.admin.v2.Table] and the + resources that serve them. All tables in an instance are + served from all + [Clusters][google.bigtable.admin.v2.Cluster] in the + instance. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + ~.instance.Instance: + A collection of Bigtable + [Tables][google.bigtable.admin.v2.Table] and the + resources that serve them. All tables in an instance are + served from all + [Clusters][google.bigtable.admin.v2.Cluster] in the + instance. """ http_options = ( - _BaseBigtableInstanceAdminRestTransport._BaseUpdateAppProfile._get_http_options() - ) - request, metadata = self._interceptor.pre_update_app_profile( - request, metadata + _BaseBigtableInstanceAdminRestTransport._BaseUpdateInstance._get_http_options() ) - transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseUpdateAppProfile._get_transcoded_request( + + request, metadata = self._interceptor.pre_update_instance(request, metadata) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseUpdateInstance._get_transcoded_request( http_options, request ) - body = _BaseBigtableInstanceAdminRestTransport._BaseUpdateAppProfile._get_request_body_json( + body = _BaseBigtableInstanceAdminRestTransport._BaseUpdateInstance._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseBigtableInstanceAdminRestTransport._BaseUpdateAppProfile._get_query_params_json( + query_params = _BaseBigtableInstanceAdminRestTransport._BaseUpdateInstance._get_query_params_json( transcoded_request ) - # Send the request - response = ( - BigtableInstanceAdminRestTransport._UpdateAppProfile._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.UpdateInstance", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, ) + + # Send the request + response = BigtableInstanceAdminRestTransport._UpdateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2759,17 +6171,45 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_app_profile(resp) + resp = instance.Instance() + pb_resp = instance.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.Instance.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.update_instance", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _UpdateCluster( - _BaseBigtableInstanceAdminRestTransport._BaseUpdateCluster, + class _UpdateLogicalView( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateLogicalView, BigtableInstanceAdminRestStub, ): def __hash__(self): - return hash("BigtableInstanceAdminRestTransport.UpdateCluster") + return hash("BigtableInstanceAdminRestTransport.UpdateLogicalView") @staticmethod def _get_response( @@ -2796,25 +6236,25 @@ def _get_response( def __call__( self, - request: instance.Cluster, + request: bigtable_instance_admin.UpdateLogicalViewRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the update cluster method over HTTP. + r"""Call the update logical view method over HTTP. Args: - request (~.instance.Cluster): - The request object. A resizable group of nodes in a particular cloud - location, capable of serving all - [Tables][google.bigtable.admin.v2.Table] in the parent - [Instance][google.bigtable.admin.v2.Instance]. + request (~.bigtable_instance_admin.UpdateLogicalViewRequest): + The request object. Request message for + BigtableInstanceAdmin.UpdateLogicalView. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -2825,31 +6265,63 @@ def __call__( """ http_options = ( - _BaseBigtableInstanceAdminRestTransport._BaseUpdateCluster._get_http_options() + _BaseBigtableInstanceAdminRestTransport._BaseUpdateLogicalView._get_http_options() ) - request, metadata = self._interceptor.pre_update_cluster(request, metadata) - transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseUpdateCluster._get_transcoded_request( + + request, metadata = self._interceptor.pre_update_logical_view( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseUpdateLogicalView._get_transcoded_request( http_options, request ) - body = _BaseBigtableInstanceAdminRestTransport._BaseUpdateCluster._get_request_body_json( + body = _BaseBigtableInstanceAdminRestTransport._BaseUpdateLogicalView._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseBigtableInstanceAdminRestTransport._BaseUpdateCluster._get_query_params_json( + query_params = _BaseBigtableInstanceAdminRestTransport._BaseUpdateLogicalView._get_query_params_json( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.UpdateLogicalView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateLogicalView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request - response = BigtableInstanceAdminRestTransport._UpdateCluster._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, + response = ( + BigtableInstanceAdminRestTransport._UpdateLogicalView._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2860,15 +6332,41 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_cluster(resp) + + resp = self._interceptor.post_update_logical_view(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_logical_view_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.update_logical_view", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateLogicalView", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _UpdateInstance( - _BaseBigtableInstanceAdminRestTransport._BaseUpdateInstance, + class _UpdateMaterializedView( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateMaterializedView, BigtableInstanceAdminRestStub, ): def __hash__(self): - return hash("BigtableInstanceAdminRestTransport.UpdateInstance") + return hash("BigtableInstanceAdminRestTransport.UpdateMaterializedView") @staticmethod def _get_response( @@ -2895,58 +6393,83 @@ def _get_response( def __call__( self, - request: instance.Instance, + request: bigtable_instance_admin.UpdateMaterializedViewRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> instance.Instance: - r"""Call the update instance method over HTTP. + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update materialized view method over HTTP. Args: - request (~.instance.Instance): - The request object. A collection of Bigtable - [Tables][google.bigtable.admin.v2.Table] and the - resources that serve them. All tables in an instance are - served from all - [Clusters][google.bigtable.admin.v2.Cluster] in the - instance. + request (~.bigtable_instance_admin.UpdateMaterializedViewRequest): + The request object. Request message for + BigtableInstanceAdmin.UpdateMaterializedView. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - ~.instance.Instance: - A collection of Bigtable - [Tables][google.bigtable.admin.v2.Table] and the - resources that serve them. All tables in an instance are - served from all - [Clusters][google.bigtable.admin.v2.Cluster] in the - instance. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseBigtableInstanceAdminRestTransport._BaseUpdateInstance._get_http_options() + _BaseBigtableInstanceAdminRestTransport._BaseUpdateMaterializedView._get_http_options() ) - request, metadata = self._interceptor.pre_update_instance(request, metadata) - transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseUpdateInstance._get_transcoded_request( + + request, metadata = self._interceptor.pre_update_materialized_view( + request, metadata + ) + transcoded_request = _BaseBigtableInstanceAdminRestTransport._BaseUpdateMaterializedView._get_transcoded_request( http_options, request ) - body = _BaseBigtableInstanceAdminRestTransport._BaseUpdateInstance._get_request_body_json( + body = _BaseBigtableInstanceAdminRestTransport._BaseUpdateMaterializedView._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseBigtableInstanceAdminRestTransport._BaseUpdateInstance._get_query_params_json( + query_params = _BaseBigtableInstanceAdminRestTransport._BaseUpdateMaterializedView._get_query_params_json( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.UpdateMaterializedView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateMaterializedView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request - response = BigtableInstanceAdminRestTransport._UpdateInstance._get_response( + response = BigtableInstanceAdminRestTransport._UpdateMaterializedView._get_response( self._host, metadata, query_params, @@ -2962,11 +6485,35 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = instance.Instance() - pb_resp = instance.Instance.pb(resp) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_instance(resp) + resp = self._interceptor.post_update_materialized_view(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_materialized_view_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.update_materialized_view", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateMaterializedView", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property @@ -2999,6 +6546,27 @@ def create_instance( # In C++ this would require a dynamic_cast return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def create_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.CreateLogicalViewRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateLogicalView(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.CreateMaterializedViewRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMaterializedView(self._session, self._host, self._interceptor) # type: ignore + @property def delete_app_profile( self, @@ -3023,6 +6591,24 @@ def delete_instance( # In C++ this would require a dynamic_cast return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_logical_view( + self, + ) -> Callable[[bigtable_instance_admin.DeleteLogicalViewRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteLogicalView(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.DeleteMaterializedViewRequest], empty_pb2.Empty + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMaterializedView(self._session, self._host, self._interceptor) # type: ignore + @property def get_app_profile( self, @@ -3055,6 +6641,26 @@ def get_instance( # In C++ this would require a dynamic_cast return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def get_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.GetLogicalViewRequest], instance.LogicalView + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetLogicalView(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.GetMaterializedViewRequest], instance.MaterializedView + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMaterializedView(self._session, self._host, self._interceptor) # type: ignore + @property def list_app_profiles( self, @@ -3099,6 +6705,28 @@ def list_instances( # In C++ this would require a dynamic_cast return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + @property + def list_logical_views( + self, + ) -> Callable[ + [bigtable_instance_admin.ListLogicalViewsRequest], + bigtable_instance_admin.ListLogicalViewsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListLogicalViews(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_materialized_views( + self, + ) -> Callable[ + [bigtable_instance_admin.ListMaterializedViewsRequest], + bigtable_instance_admin.ListMaterializedViewsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMaterializedViews(self._session, self._host, self._interceptor) # type: ignore + @property def partial_update_cluster( self, @@ -3160,6 +6788,27 @@ def update_instance(self) -> Callable[[instance.Instance], instance.Instance]: # In C++ this would require a dynamic_cast return self._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def update_logical_view( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateLogicalViewRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateLogicalView(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_materialized_view( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateMaterializedViewRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMaterializedView(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest_base.py b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest_base.py index 7b0c1a4ba..5851243ed 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest_base.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest_base.py @@ -269,6 +269,126 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseCreateLogicalView: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "logicalViewId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/instances/*}/logicalViews", + "body": "logical_view", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable_instance_admin.CreateLogicalViewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableInstanceAdminRestTransport._BaseCreateLogicalView._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateMaterializedView: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "materializedViewId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/instances/*}/materializedViews", + "body": "materialized_view", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable_instance_admin.CreateMaterializedViewRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableInstanceAdminRestTransport._BaseCreateMaterializedView._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseDeleteAppProfile: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -412,6 +532,102 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseDeleteLogicalView: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/instances/*/logicalViews/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable_instance_admin.DeleteLogicalViewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteLogicalView._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteMaterializedView: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/instances/*/materializedViews/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable_instance_admin.DeleteMaterializedViewRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableInstanceAdminRestTransport._BaseDeleteMaterializedView._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetAppProfile: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -528,6 +744,16 @@ def _get_http_options(): "uri": "/v2/{resource=projects/*/instances/*}:getIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v2/{resource=projects/*/instances/*/materializedViews/*}:getIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{resource=projects/*/instances/*/logicalViews/*}:getIamPolicy", + "body": "*", + }, ] return http_options @@ -610,6 +836,100 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetLogicalView: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/instances/*/logicalViews/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable_instance_admin.GetLogicalViewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableInstanceAdminRestTransport._BaseGetLogicalView._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetMaterializedView: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/instances/*/materializedViews/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable_instance_admin.GetMaterializedViewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableInstanceAdminRestTransport._BaseGetMaterializedView._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseListAppProfiles: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -798,6 +1118,102 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseListLogicalViews: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/instances/*}/logicalViews", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable_instance_admin.ListLogicalViewsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableInstanceAdminRestTransport._BaseListLogicalViews._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListMaterializedViews: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/instances/*}/materializedViews", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable_instance_admin.ListMaterializedViewsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableInstanceAdminRestTransport._BaseListMaterializedViews._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BasePartialUpdateCluster: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -940,6 +1356,16 @@ def _get_http_options(): "uri": "/v2/{resource=projects/*/instances/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v2/{resource=projects/*/instances/*/materializedViews/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{resource=projects/*/instances/*/logicalViews/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -997,6 +1423,16 @@ def _get_http_options(): "uri": "/v2/{resource=projects/*/instances/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v2/{resource=projects/*/instances/*/materializedViews/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{resource=projects/*/instances/*/logicalViews/*}:testIamPermissions", + "body": "*", + }, ] return http_options @@ -1190,5 +1626,121 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseUpdateLogicalView: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{logical_view.name=projects/*/instances/*/logicalViews/*}", + "body": "logical_view", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable_instance_admin.UpdateLogicalViewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateLogicalView._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateMaterializedView: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{materialized_view.name=projects/*/instances/*/materializedViews/*}", + "body": "materialized_view", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable_instance_admin.UpdateMaterializedViewRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateMaterializedView._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + __all__ = ("_BaseBigtableInstanceAdminRestTransport",) diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/async_client.py b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/async_client.py index 2e9eb13eb..a10691b71 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/async_client.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/async_client.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import logging as std_logging from collections import OrderedDict import re from typing import ( @@ -49,6 +50,7 @@ from google.cloud.bigtable_admin_v2.types import bigtable_table_admin from google.cloud.bigtable_admin_v2.types import table from google.cloud.bigtable_admin_v2.types import table as gba_table +from google.cloud.bigtable_admin_v2.types import types 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 @@ -57,6 +59,15 @@ from .transports.grpc_asyncio import BigtableTableAdminGrpcAsyncIOTransport from .client import BigtableTableAdminClient +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + class BigtableTableAdminAsyncClient: """Service for creating, configuring, and deleting Cloud @@ -289,6 +300,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.bigtable.admin_v2.BigtableTableAdminAsyncClient`.", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "credentialsType": None, + }, + ) + async def create_table( self, request: Optional[Union[bigtable_table_admin.CreateTableRequest, dict]] = None, @@ -298,7 +331,7 @@ async def create_table( table: Optional[gba_table.Table] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gba_table.Table: r"""Creates a new table in the specified instance. The table can be created with a full set of initial @@ -333,8 +366,10 @@ async def create_table( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Table: @@ -347,7 +382,10 @@ async def create_table( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, table_id, table]) + flattened_params = [parent, table_id, table] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -405,7 +443,7 @@ async def create_table_from_snapshot( source_snapshot: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Creates a new table from the specified snapshot. The target table must not exist. The snapshot and the table @@ -457,8 +495,10 @@ async def create_table_from_snapshot( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -472,7 +512,10 @@ async def create_table_from_snapshot( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, table_id, source_snapshot]) + flattened_params = [parent, table_id, source_snapshot] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -534,7 +577,7 @@ async def list_tables( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListTablesAsyncPager: r"""Lists all tables served from a specified instance. @@ -553,8 +596,10 @@ async def list_tables( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_table_admin.pagers.ListTablesAsyncPager: @@ -568,7 +613,10 @@ async def list_tables( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -629,7 +677,7 @@ async def get_table( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Table: r"""Gets metadata information about the specified table. @@ -648,8 +696,10 @@ async def get_table( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Table: @@ -662,7 +712,10 @@ async def get_table( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -713,7 +766,7 @@ async def update_table( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Updates a specified table. @@ -740,6 +793,7 @@ async def update_table( - ``change_stream_config`` - ``change_stream_config.retention_period`` - ``deletion_protection`` + - ``row_key_schema`` If ``column_families`` is set in ``update_mask``, it will return an UNIMPLEMENTED error. @@ -750,8 +804,10 @@ async def update_table( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -765,7 +821,10 @@ async def update_table( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table, update_mask]) + flattened_params = [table, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -827,7 +886,7 @@ async def delete_table( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Permanently deletes a specified table and all of its data. @@ -847,13 +906,18 @@ async def delete_table( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -902,7 +966,7 @@ async def undelete_table( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Restores a specified table which was accidentally deleted. @@ -922,8 +986,10 @@ async def undelete_table( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -937,7 +1003,10 @@ async def undelete_table( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -999,7 +1068,7 @@ async def create_authorized_view( authorized_view_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Creates a new AuthorizedView in a table. @@ -1035,8 +1104,10 @@ async def create_authorized_view( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -1051,7 +1122,10 @@ async def create_authorized_view( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, authorized_view, authorized_view_id]) + flattened_params = [parent, authorized_view, authorized_view_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1115,7 +1189,7 @@ async def list_authorized_views( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAuthorizedViewsAsyncPager: r"""Lists all AuthorizedViews from a specific table. @@ -1134,8 +1208,10 @@ async def list_authorized_views( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_table_admin.pagers.ListAuthorizedViewsAsyncPager: @@ -1149,7 +1225,10 @@ async def list_authorized_views( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1212,7 +1291,7 @@ async def get_authorized_view( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.AuthorizedView: r"""Gets information from a specified AuthorizedView. @@ -1231,8 +1310,10 @@ async def get_authorized_view( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.AuthorizedView: @@ -1247,7 +1328,10 @@ async def get_authorized_view( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1300,7 +1384,7 @@ async def update_authorized_view( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Updates an AuthorizedView in a table. @@ -1333,8 +1417,10 @@ async def update_authorized_view( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -1349,7 +1435,10 @@ async def update_authorized_view( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([authorized_view, update_mask]) + flattened_params = [authorized_view, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1413,7 +1502,7 @@ async def delete_authorized_view( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Permanently deletes a specified AuthorizedView. @@ -1432,13 +1521,18 @@ async def delete_authorized_view( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1492,7 +1586,7 @@ async def modify_column_families( ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Table: r"""Performs a series of column family modifications on the specified table. Either all or none of the @@ -1527,8 +1621,10 @@ async def modify_column_families( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Table: @@ -1541,7 +1637,10 @@ async def modify_column_families( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, modifications]) + flattened_params = [name, modifications] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1592,7 +1691,7 @@ async def drop_row_range( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Permanently drop/delete a row range from a specified table. The request can specify whether to delete all @@ -1606,8 +1705,10 @@ async def drop_row_range( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Use the request object if provided (there's no risk of modifying the input as @@ -1647,7 +1748,7 @@ async def generate_consistency_token( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_table_admin.GenerateConsistencyTokenResponse: r"""Generates a consistency token for a Table, which can be used in CheckConsistency to check whether mutations @@ -1670,8 +1771,10 @@ async def generate_consistency_token( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.GenerateConsistencyTokenResponse: @@ -1682,7 +1785,10 @@ async def generate_consistency_token( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1737,7 +1843,7 @@ async def check_consistency( consistency_token: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_table_admin.CheckConsistencyResponse: r"""Checks replication consistency based on a consistency token, that is, if replication has caught up based on @@ -1766,8 +1872,10 @@ async def check_consistency( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.CheckConsistencyResponse: @@ -1778,7 +1886,10 @@ async def check_consistency( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, consistency_token]) + flattened_params = [name, consistency_token] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1835,7 +1946,7 @@ async def snapshot_table( description: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Creates a new snapshot in the specified cluster from the specified source table. The cluster and the table @@ -1893,8 +2004,10 @@ async def snapshot_table( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -1915,7 +2028,10 @@ async def snapshot_table( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, cluster, snapshot_id, description]) + flattened_params = [name, cluster, snapshot_id, description] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1979,7 +2095,7 @@ async def get_snapshot( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Snapshot: r"""Gets metadata information about the specified snapshot. @@ -2012,8 +2128,10 @@ async def get_snapshot( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Snapshot: @@ -2035,7 +2153,10 @@ async def get_snapshot( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2087,7 +2208,7 @@ async def list_snapshots( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListSnapshotsAsyncPager: r"""Lists all snapshots associated with the specified cluster. @@ -2123,8 +2244,10 @@ async def list_snapshots( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_table_admin.pagers.ListSnapshotsAsyncPager: @@ -2145,7 +2268,10 @@ async def list_snapshots( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2208,7 +2334,7 @@ async def delete_snapshot( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Permanently deletes the specified snapshot. @@ -2241,13 +2367,18 @@ async def delete_snapshot( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2296,7 +2427,7 @@ async def create_backup( backup: Optional[table.Backup] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Starts creating a new Cloud Bigtable Backup. The returned backup [long-running operation][google.longrunning.Operation] can be @@ -2341,8 +2472,10 @@ async def create_backup( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -2356,7 +2489,10 @@ async def create_backup( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, backup_id, backup]) + flattened_params = [parent, backup_id, backup] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2418,7 +2554,7 @@ async def get_backup( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Backup: r"""Gets metadata on a pending or completed Cloud Bigtable Backup. @@ -2437,8 +2573,10 @@ async def get_backup( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Backup: @@ -2447,7 +2585,10 @@ async def get_backup( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2498,7 +2639,7 @@ async def update_backup( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Backup: r"""Updates a pending or completed Cloud Bigtable Backup. @@ -2532,8 +2673,10 @@ async def update_backup( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Backup: @@ -2542,7 +2685,10 @@ async def update_backup( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([backup, update_mask]) + flattened_params = [backup, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2596,7 +2742,7 @@ async def delete_backup( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a pending or completed Cloud Bigtable backup. @@ -2615,13 +2761,18 @@ async def delete_backup( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2668,7 +2819,7 @@ async def list_backups( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListBackupsAsyncPager: r"""Lists Cloud Bigtable backups. Returns both completed and pending backups. @@ -2691,8 +2842,10 @@ async def list_backups( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_table_admin.pagers.ListBackupsAsyncPager: @@ -2706,7 +2859,10 @@ async def list_backups( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2766,7 +2922,7 @@ async def restore_table( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Create a new table by restoring from a completed backup. The returned table [long-running @@ -2784,8 +2940,10 @@ async def restore_table( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -2846,7 +3004,7 @@ async def copy_backup( expire_time: Optional[timestamp_pb2.Timestamp] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Copy a Cloud Bigtable backup to a new backup in the destination cluster located in the destination instance @@ -2903,8 +3061,10 @@ async def copy_backup( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -2918,7 +3078,10 @@ async def copy_backup( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, backup_id, source_backup, expire_time]) + flattened_params = [parent, backup_id, source_backup, expire_time] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2982,7 +3145,7 @@ async def get_iam_policy( resource: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Gets the access control policy for a Table or Backup resource. Returns an empty policy if the resource exists @@ -3003,8 +3166,10 @@ async def get_iam_policy( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.policy_pb2.Policy: @@ -3043,7 +3208,10 @@ async def get_iam_policy( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -3090,7 +3258,7 @@ async def set_iam_policy( resource: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Sets the access control policy on a Table or Backup resource. Replaces any existing policy. @@ -3110,8 +3278,10 @@ async def set_iam_policy( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.policy_pb2.Policy: @@ -3150,7 +3320,10 @@ async def set_iam_policy( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -3198,7 +3371,7 @@ async def test_iam_permissions( permissions: Optional[MutableSequence[str]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that the caller has on the specified Table or Backup resource. @@ -3227,8 +3400,10 @@ async def test_iam_permissions( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: @@ -3237,7 +3412,10 @@ async def test_iam_permissions( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) + flattened_params = [resource, permissions] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/client.py b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/client.py index 502f0085c..3204f43a1 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/client.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/client.py @@ -14,6 +14,9 @@ # limitations under the License. # from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging import os import re from typing import ( @@ -48,12 +51,22 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.bigtable_admin_v2.services.bigtable_table_admin import pagers from google.cloud.bigtable_admin_v2.types import bigtable_table_admin from google.cloud.bigtable_admin_v2.types import table from google.cloud.bigtable_admin_v2.types import table as gba_table +from google.cloud.bigtable_admin_v2.types import types 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 @@ -623,6 +636,33 @@ def _validate_universe_domain(self): # NOTE (b/349488459): universe validation is disabled until further notice. return True + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + @property def api_endpoint(self): """Return the API endpoint used by the client instance. @@ -731,6 +771,10 @@ def __init__( # Initialize the universe domain validation. self._is_universe_domain_valid = False + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: raise ValueError( @@ -797,6 +841,29 @@ def __init__( api_audience=self._client_options.api_audience, ) + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.bigtable.admin_v2.BigtableTableAdminClient`.", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "credentialsType": None, + }, + ) + def create_table( self, request: Optional[Union[bigtable_table_admin.CreateTableRequest, dict]] = None, @@ -806,7 +873,7 @@ def create_table( table: Optional[gba_table.Table] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gba_table.Table: r"""Creates a new table in the specified instance. The table can be created with a full set of initial @@ -841,8 +908,10 @@ def create_table( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Table: @@ -855,7 +924,10 @@ def create_table( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, table_id, table]) + flattened_params = [parent, table_id, table] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -910,7 +982,7 @@ def create_table_from_snapshot( source_snapshot: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Creates a new table from the specified snapshot. The target table must not exist. The snapshot and the table @@ -962,8 +1034,10 @@ def create_table_from_snapshot( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -977,7 +1051,10 @@ def create_table_from_snapshot( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, table_id, source_snapshot]) + flattened_params = [parent, table_id, source_snapshot] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1038,7 +1115,7 @@ def list_tables( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListTablesPager: r"""Lists all tables served from a specified instance. @@ -1057,8 +1134,10 @@ def list_tables( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_table_admin.pagers.ListTablesPager: @@ -1072,7 +1151,10 @@ def list_tables( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1130,7 +1212,7 @@ def get_table( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Table: r"""Gets metadata information about the specified table. @@ -1149,8 +1231,10 @@ def get_table( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Table: @@ -1163,7 +1247,10 @@ def get_table( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1211,7 +1298,7 @@ def update_table( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Updates a specified table. @@ -1238,6 +1325,7 @@ def update_table( - ``change_stream_config`` - ``change_stream_config.retention_period`` - ``deletion_protection`` + - ``row_key_schema`` If ``column_families`` is set in ``update_mask``, it will return an UNIMPLEMENTED error. @@ -1248,8 +1336,10 @@ def update_table( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1263,7 +1353,10 @@ def update_table( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table, update_mask]) + flattened_params = [table, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1322,7 +1415,7 @@ def delete_table( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Permanently deletes a specified table and all of its data. @@ -1342,13 +1435,18 @@ def delete_table( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1394,7 +1492,7 @@ def undelete_table( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Restores a specified table which was accidentally deleted. @@ -1414,8 +1512,10 @@ def undelete_table( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1429,7 +1529,10 @@ def undelete_table( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1488,7 +1591,7 @@ def create_authorized_view( authorized_view_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Creates a new AuthorizedView in a table. @@ -1524,8 +1627,10 @@ def create_authorized_view( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1540,7 +1645,10 @@ def create_authorized_view( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, authorized_view, authorized_view_id]) + flattened_params = [parent, authorized_view, authorized_view_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1601,7 +1709,7 @@ def list_authorized_views( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAuthorizedViewsPager: r"""Lists all AuthorizedViews from a specific table. @@ -1620,8 +1728,10 @@ def list_authorized_views( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_table_admin.pagers.ListAuthorizedViewsPager: @@ -1635,7 +1745,10 @@ def list_authorized_views( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1695,7 +1808,7 @@ def get_authorized_view( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.AuthorizedView: r"""Gets information from a specified AuthorizedView. @@ -1714,8 +1827,10 @@ def get_authorized_view( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.AuthorizedView: @@ -1730,7 +1845,10 @@ def get_authorized_view( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1780,7 +1898,7 @@ def update_authorized_view( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Updates an AuthorizedView in a table. @@ -1813,8 +1931,10 @@ def update_authorized_view( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1829,7 +1949,10 @@ def update_authorized_view( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([authorized_view, update_mask]) + flattened_params = [authorized_view, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1890,7 +2013,7 @@ def delete_authorized_view( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Permanently deletes a specified AuthorizedView. @@ -1909,13 +2032,18 @@ def delete_authorized_view( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1966,7 +2094,7 @@ def modify_column_families( ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Table: r"""Performs a series of column family modifications on the specified table. Either all or none of the @@ -2001,8 +2129,10 @@ def modify_column_families( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Table: @@ -2015,7 +2145,10 @@ def modify_column_families( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, modifications]) + flattened_params = [name, modifications] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2063,7 +2196,7 @@ def drop_row_range( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Permanently drop/delete a row range from a specified table. The request can specify whether to delete all @@ -2077,8 +2210,10 @@ def drop_row_range( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Use the request object if provided (there's no risk of modifying the input as @@ -2116,7 +2251,7 @@ def generate_consistency_token( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_table_admin.GenerateConsistencyTokenResponse: r"""Generates a consistency token for a Table, which can be used in CheckConsistency to check whether mutations @@ -2139,8 +2274,10 @@ def generate_consistency_token( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.GenerateConsistencyTokenResponse: @@ -2151,7 +2288,10 @@ def generate_consistency_token( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2205,7 +2345,7 @@ def check_consistency( consistency_token: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_table_admin.CheckConsistencyResponse: r"""Checks replication consistency based on a consistency token, that is, if replication has caught up based on @@ -2234,8 +2374,10 @@ def check_consistency( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.CheckConsistencyResponse: @@ -2246,7 +2388,10 @@ def check_consistency( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, consistency_token]) + flattened_params = [name, consistency_token] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2300,7 +2445,7 @@ def snapshot_table( description: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Creates a new snapshot in the specified cluster from the specified source table. The cluster and the table @@ -2358,8 +2503,10 @@ def snapshot_table( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -2380,7 +2527,10 @@ def snapshot_table( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, cluster, snapshot_id, description]) + flattened_params = [name, cluster, snapshot_id, description] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2441,7 +2591,7 @@ def get_snapshot( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Snapshot: r"""Gets metadata information about the specified snapshot. @@ -2474,8 +2624,10 @@ def get_snapshot( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Snapshot: @@ -2497,7 +2649,10 @@ def get_snapshot( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2546,7 +2701,7 @@ def list_snapshots( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListSnapshotsPager: r"""Lists all snapshots associated with the specified cluster. @@ -2582,8 +2737,10 @@ def list_snapshots( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_table_admin.pagers.ListSnapshotsPager: @@ -2604,7 +2761,10 @@ def list_snapshots( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2664,7 +2824,7 @@ def delete_snapshot( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Permanently deletes the specified snapshot. @@ -2697,13 +2857,18 @@ def delete_snapshot( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2749,7 +2914,7 @@ def create_backup( backup: Optional[table.Backup] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Starts creating a new Cloud Bigtable Backup. The returned backup [long-running operation][google.longrunning.Operation] can be @@ -2794,8 +2959,10 @@ def create_backup( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -2809,7 +2976,10 @@ def create_backup( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, backup_id, backup]) + flattened_params = [parent, backup_id, backup] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2868,7 +3038,7 @@ def get_backup( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Backup: r"""Gets metadata on a pending or completed Cloud Bigtable Backup. @@ -2887,8 +3057,10 @@ def get_backup( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Backup: @@ -2897,7 +3069,10 @@ def get_backup( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -2945,7 +3120,7 @@ def update_backup( update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Backup: r"""Updates a pending or completed Cloud Bigtable Backup. @@ -2979,8 +3154,10 @@ def update_backup( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.types.Backup: @@ -2989,7 +3166,10 @@ def update_backup( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([backup, update_mask]) + flattened_params = [backup, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -3040,7 +3220,7 @@ def delete_backup( name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Deletes a pending or completed Cloud Bigtable backup. @@ -3059,13 +3239,18 @@ def delete_backup( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -3109,7 +3294,7 @@ def list_backups( parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListBackupsPager: r"""Lists Cloud Bigtable backups. Returns both completed and pending backups. @@ -3132,8 +3317,10 @@ def list_backups( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_admin_v2.services.bigtable_table_admin.pagers.ListBackupsPager: @@ -3147,7 +3334,10 @@ def list_backups( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -3204,7 +3394,7 @@ def restore_table( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Create a new table by restoring from a completed backup. The returned table [long-running @@ -3222,8 +3412,10 @@ def restore_table( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -3282,7 +3474,7 @@ def copy_backup( expire_time: Optional[timestamp_pb2.Timestamp] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Copy a Cloud Bigtable backup to a new backup in the destination cluster located in the destination instance @@ -3339,8 +3531,10 @@ def copy_backup( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -3354,7 +3548,10 @@ def copy_backup( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, backup_id, source_backup, expire_time]) + flattened_params = [parent, backup_id, source_backup, expire_time] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -3415,7 +3612,7 @@ def get_iam_policy( resource: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Gets the access control policy for a Table or Backup resource. Returns an empty policy if the resource exists @@ -3436,8 +3633,10 @@ def get_iam_policy( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.policy_pb2.Policy: @@ -3476,7 +3675,10 @@ def get_iam_policy( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -3524,7 +3726,7 @@ def set_iam_policy( resource: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Sets the access control policy on a Table or Backup resource. Replaces any existing policy. @@ -3544,8 +3746,10 @@ def set_iam_policy( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.policy_pb2.Policy: @@ -3584,7 +3788,10 @@ def set_iam_policy( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) + flattened_params = [resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -3633,7 +3840,7 @@ def test_iam_permissions( permissions: Optional[MutableSequence[str]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that the caller has on the specified Table or Backup resource. @@ -3662,8 +3869,10 @@ def test_iam_permissions( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: @@ -3672,7 +3881,10 @@ def test_iam_permissions( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) + flattened_params = [resource, permissions] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/pagers.py b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/pagers.py index 5e20fbc5f..4351a5814 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/pagers.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/pagers.py @@ -67,7 +67,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -81,8 +81,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_table_admin.ListTablesRequest(request) @@ -141,7 +143,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -155,8 +157,10 @@ def __init__( retry (google.api_core.retry.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_table_admin.ListTablesRequest(request) @@ -219,7 +223,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -233,8 +237,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_table_admin.ListAuthorizedViewsRequest(request) @@ -295,7 +301,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -309,8 +315,10 @@ def __init__( retry (google.api_core.retry.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_table_admin.ListAuthorizedViewsRequest(request) @@ -375,7 +383,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -389,8 +397,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_table_admin.ListSnapshotsRequest(request) @@ -449,7 +459,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -463,8 +473,10 @@ def __init__( retry (google.api_core.retry.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_table_admin.ListSnapshotsRequest(request) @@ -527,7 +539,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -541,8 +553,10 @@ def __init__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_table_admin.ListBackupsRequest(request) @@ -601,7 +615,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -615,8 +629,10 @@ def __init__( retry (google.api_core.retry.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = bigtable_table_admin.ListBackupsRequest(request) diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/base.py b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/base.py index bb7875d87..5f74859a5 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/base.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/base.py @@ -258,9 +258,9 @@ def _prep_wrapped_messages(self, client_info): core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), - deadline=60.0, + deadline=3600.0, ), - default_timeout=60.0, + default_timeout=3600.0, client_info=client_info, ), self.snapshot_table: gapic_v1.method.wrap_method( diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/grpc.py b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/grpc.py index 8b0eadbbc..59c701b8f 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/grpc.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union @@ -22,8 +25,11 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message import grpc # type: ignore +import proto # type: ignore from google.cloud.bigtable_admin_v2.types import bigtable_table_admin from google.cloud.bigtable_admin_v2.types import table @@ -34,6 +40,81 @@ from google.protobuf import empty_pb2 # type: ignore from .base import BigtableTableAdminTransport, DEFAULT_CLIENT_INFO +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class BigtableTableAdminGrpcTransport(BigtableTableAdminTransport): """gRPC backend transport for BigtableTableAdmin. @@ -192,7 +273,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod @@ -256,7 +342,9 @@ def operations_client(self) -> operations_v1.OperationsClient: """ # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) # Return the client from cache. return self._operations_client @@ -282,7 +370,7 @@ def create_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_table" not in self._stubs: - self._stubs["create_table"] = self.grpc_channel.unary_unary( + self._stubs["create_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CreateTable", request_serializer=bigtable_table_admin.CreateTableRequest.serialize, response_deserializer=gba_table.Table.deserialize, @@ -319,7 +407,9 @@ def create_table_from_snapshot( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_table_from_snapshot" not in self._stubs: - self._stubs["create_table_from_snapshot"] = self.grpc_channel.unary_unary( + self._stubs[ + "create_table_from_snapshot" + ] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CreateTableFromSnapshot", request_serializer=bigtable_table_admin.CreateTableFromSnapshotRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -348,7 +438,7 @@ def list_tables( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_tables" not in self._stubs: - self._stubs["list_tables"] = self.grpc_channel.unary_unary( + self._stubs["list_tables"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/ListTables", request_serializer=bigtable_table_admin.ListTablesRequest.serialize, response_deserializer=bigtable_table_admin.ListTablesResponse.deserialize, @@ -374,7 +464,7 @@ def get_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_table" not in self._stubs: - self._stubs["get_table"] = self.grpc_channel.unary_unary( + self._stubs["get_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GetTable", request_serializer=bigtable_table_admin.GetTableRequest.serialize, response_deserializer=table.Table.deserialize, @@ -400,7 +490,7 @@ def update_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_table" not in self._stubs: - self._stubs["update_table"] = self.grpc_channel.unary_unary( + self._stubs["update_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/UpdateTable", request_serializer=bigtable_table_admin.UpdateTableRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -427,7 +517,7 @@ def delete_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_table" not in self._stubs: - self._stubs["delete_table"] = self.grpc_channel.unary_unary( + self._stubs["delete_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/DeleteTable", request_serializer=bigtable_table_admin.DeleteTableRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -456,7 +546,7 @@ def undelete_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "undelete_table" not in self._stubs: - self._stubs["undelete_table"] = self.grpc_channel.unary_unary( + self._stubs["undelete_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/UndeleteTable", request_serializer=bigtable_table_admin.UndeleteTableRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -484,7 +574,7 @@ def create_authorized_view( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_authorized_view" not in self._stubs: - self._stubs["create_authorized_view"] = self.grpc_channel.unary_unary( + self._stubs["create_authorized_view"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CreateAuthorizedView", request_serializer=bigtable_table_admin.CreateAuthorizedViewRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -513,7 +603,7 @@ def list_authorized_views( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_authorized_views" not in self._stubs: - self._stubs["list_authorized_views"] = self.grpc_channel.unary_unary( + self._stubs["list_authorized_views"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/ListAuthorizedViews", request_serializer=bigtable_table_admin.ListAuthorizedViewsRequest.serialize, response_deserializer=bigtable_table_admin.ListAuthorizedViewsResponse.deserialize, @@ -541,7 +631,7 @@ def get_authorized_view( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_authorized_view" not in self._stubs: - self._stubs["get_authorized_view"] = self.grpc_channel.unary_unary( + self._stubs["get_authorized_view"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GetAuthorizedView", request_serializer=bigtable_table_admin.GetAuthorizedViewRequest.serialize, response_deserializer=table.AuthorizedView.deserialize, @@ -569,7 +659,7 @@ def update_authorized_view( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_authorized_view" not in self._stubs: - self._stubs["update_authorized_view"] = self.grpc_channel.unary_unary( + self._stubs["update_authorized_view"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/UpdateAuthorizedView", request_serializer=bigtable_table_admin.UpdateAuthorizedViewRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -595,7 +685,7 @@ def delete_authorized_view( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_authorized_view" not in self._stubs: - self._stubs["delete_authorized_view"] = self.grpc_channel.unary_unary( + self._stubs["delete_authorized_view"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/DeleteAuthorizedView", request_serializer=bigtable_table_admin.DeleteAuthorizedViewRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -625,7 +715,7 @@ def modify_column_families( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "modify_column_families" not in self._stubs: - self._stubs["modify_column_families"] = self.grpc_channel.unary_unary( + self._stubs["modify_column_families"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/ModifyColumnFamilies", request_serializer=bigtable_table_admin.ModifyColumnFamiliesRequest.serialize, response_deserializer=table.Table.deserialize, @@ -654,7 +744,7 @@ def drop_row_range( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "drop_row_range" not in self._stubs: - self._stubs["drop_row_range"] = self.grpc_channel.unary_unary( + self._stubs["drop_row_range"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/DropRowRange", request_serializer=bigtable_table_admin.DropRowRangeRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -687,7 +777,9 @@ def generate_consistency_token( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "generate_consistency_token" not in self._stubs: - self._stubs["generate_consistency_token"] = self.grpc_channel.unary_unary( + self._stubs[ + "generate_consistency_token" + ] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GenerateConsistencyToken", request_serializer=bigtable_table_admin.GenerateConsistencyTokenRequest.serialize, response_deserializer=bigtable_table_admin.GenerateConsistencyTokenResponse.deserialize, @@ -719,7 +811,7 @@ def check_consistency( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "check_consistency" not in self._stubs: - self._stubs["check_consistency"] = self.grpc_channel.unary_unary( + self._stubs["check_consistency"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CheckConsistency", request_serializer=bigtable_table_admin.CheckConsistencyRequest.serialize, response_deserializer=bigtable_table_admin.CheckConsistencyResponse.deserialize, @@ -756,7 +848,7 @@ def snapshot_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "snapshot_table" not in self._stubs: - self._stubs["snapshot_table"] = self.grpc_channel.unary_unary( + self._stubs["snapshot_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/SnapshotTable", request_serializer=bigtable_table_admin.SnapshotTableRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -789,7 +881,7 @@ def get_snapshot( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_snapshot" not in self._stubs: - self._stubs["get_snapshot"] = self.grpc_channel.unary_unary( + self._stubs["get_snapshot"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GetSnapshot", request_serializer=bigtable_table_admin.GetSnapshotRequest.serialize, response_deserializer=table.Snapshot.deserialize, @@ -825,7 +917,7 @@ def list_snapshots( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_snapshots" not in self._stubs: - self._stubs["list_snapshots"] = self.grpc_channel.unary_unary( + self._stubs["list_snapshots"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/ListSnapshots", request_serializer=bigtable_table_admin.ListSnapshotsRequest.serialize, response_deserializer=bigtable_table_admin.ListSnapshotsResponse.deserialize, @@ -858,7 +950,7 @@ def delete_snapshot( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_snapshot" not in self._stubs: - self._stubs["delete_snapshot"] = self.grpc_channel.unary_unary( + self._stubs["delete_snapshot"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/DeleteSnapshot", request_serializer=bigtable_table_admin.DeleteSnapshotRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -892,7 +984,7 @@ def create_backup( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_backup" not in self._stubs: - self._stubs["create_backup"] = self.grpc_channel.unary_unary( + self._stubs["create_backup"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CreateBackup", request_serializer=bigtable_table_admin.CreateBackupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -919,7 +1011,7 @@ def get_backup( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_backup" not in self._stubs: - self._stubs["get_backup"] = self.grpc_channel.unary_unary( + self._stubs["get_backup"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GetBackup", request_serializer=bigtable_table_admin.GetBackupRequest.serialize, response_deserializer=table.Backup.deserialize, @@ -945,7 +1037,7 @@ def update_backup( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_backup" not in self._stubs: - self._stubs["update_backup"] = self.grpc_channel.unary_unary( + self._stubs["update_backup"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/UpdateBackup", request_serializer=bigtable_table_admin.UpdateBackupRequest.serialize, response_deserializer=table.Backup.deserialize, @@ -971,7 +1063,7 @@ def delete_backup( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_backup" not in self._stubs: - self._stubs["delete_backup"] = self.grpc_channel.unary_unary( + self._stubs["delete_backup"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/DeleteBackup", request_serializer=bigtable_table_admin.DeleteBackupRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -1001,7 +1093,7 @@ def list_backups( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_backups" not in self._stubs: - self._stubs["list_backups"] = self.grpc_channel.unary_unary( + self._stubs["list_backups"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/ListBackups", request_serializer=bigtable_table_admin.ListBackupsRequest.serialize, response_deserializer=bigtable_table_admin.ListBackupsResponse.deserialize, @@ -1034,7 +1126,7 @@ def restore_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "restore_table" not in self._stubs: - self._stubs["restore_table"] = self.grpc_channel.unary_unary( + self._stubs["restore_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/RestoreTable", request_serializer=bigtable_table_admin.RestoreTableRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -1062,7 +1154,7 @@ def copy_backup( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "copy_backup" not in self._stubs: - self._stubs["copy_backup"] = self.grpc_channel.unary_unary( + self._stubs["copy_backup"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CopyBackup", request_serializer=bigtable_table_admin.CopyBackupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -1090,7 +1182,7 @@ def get_iam_policy( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GetIamPolicy", request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -1117,7 +1209,7 @@ def set_iam_policy( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/SetIamPolicy", request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -1147,7 +1239,7 @@ def test_iam_permissions( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/TestIamPermissions", request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, @@ -1155,7 +1247,7 @@ def test_iam_permissions( return self._stubs["test_iam_permissions"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/grpc_asyncio.py b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/grpc_asyncio.py index 520c7c83c..751828e68 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/grpc_asyncio.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import pickle +import logging as std_logging import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union @@ -24,8 +27,11 @@ from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.bigtable_admin_v2.types import bigtable_table_admin @@ -38,6 +44,82 @@ from .base import BigtableTableAdminTransport, DEFAULT_CLIENT_INFO from .grpc import BigtableTableAdminGrpcTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class BigtableTableAdminGrpcAsyncIOTransport(BigtableTableAdminTransport): """gRPC AsyncIO backend transport for BigtableTableAdmin. @@ -239,10 +321,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel self._wrap_with_kind = ( "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters ) + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @property @@ -265,7 +350,7 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel + self._logged_channel ) # Return the client from cache. @@ -294,7 +379,7 @@ def create_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_table" not in self._stubs: - self._stubs["create_table"] = self.grpc_channel.unary_unary( + self._stubs["create_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CreateTable", request_serializer=bigtable_table_admin.CreateTableRequest.serialize, response_deserializer=gba_table.Table.deserialize, @@ -332,7 +417,9 @@ def create_table_from_snapshot( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_table_from_snapshot" not in self._stubs: - self._stubs["create_table_from_snapshot"] = self.grpc_channel.unary_unary( + self._stubs[ + "create_table_from_snapshot" + ] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CreateTableFromSnapshot", request_serializer=bigtable_table_admin.CreateTableFromSnapshotRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -361,7 +448,7 @@ def list_tables( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_tables" not in self._stubs: - self._stubs["list_tables"] = self.grpc_channel.unary_unary( + self._stubs["list_tables"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/ListTables", request_serializer=bigtable_table_admin.ListTablesRequest.serialize, response_deserializer=bigtable_table_admin.ListTablesResponse.deserialize, @@ -387,7 +474,7 @@ def get_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_table" not in self._stubs: - self._stubs["get_table"] = self.grpc_channel.unary_unary( + self._stubs["get_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GetTable", request_serializer=bigtable_table_admin.GetTableRequest.serialize, response_deserializer=table.Table.deserialize, @@ -415,7 +502,7 @@ def update_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_table" not in self._stubs: - self._stubs["update_table"] = self.grpc_channel.unary_unary( + self._stubs["update_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/UpdateTable", request_serializer=bigtable_table_admin.UpdateTableRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -444,7 +531,7 @@ def delete_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_table" not in self._stubs: - self._stubs["delete_table"] = self.grpc_channel.unary_unary( + self._stubs["delete_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/DeleteTable", request_serializer=bigtable_table_admin.DeleteTableRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -473,7 +560,7 @@ def undelete_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "undelete_table" not in self._stubs: - self._stubs["undelete_table"] = self.grpc_channel.unary_unary( + self._stubs["undelete_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/UndeleteTable", request_serializer=bigtable_table_admin.UndeleteTableRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -502,7 +589,7 @@ def create_authorized_view( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_authorized_view" not in self._stubs: - self._stubs["create_authorized_view"] = self.grpc_channel.unary_unary( + self._stubs["create_authorized_view"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CreateAuthorizedView", request_serializer=bigtable_table_admin.CreateAuthorizedViewRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -531,7 +618,7 @@ def list_authorized_views( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_authorized_views" not in self._stubs: - self._stubs["list_authorized_views"] = self.grpc_channel.unary_unary( + self._stubs["list_authorized_views"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/ListAuthorizedViews", request_serializer=bigtable_table_admin.ListAuthorizedViewsRequest.serialize, response_deserializer=bigtable_table_admin.ListAuthorizedViewsResponse.deserialize, @@ -559,7 +646,7 @@ def get_authorized_view( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_authorized_view" not in self._stubs: - self._stubs["get_authorized_view"] = self.grpc_channel.unary_unary( + self._stubs["get_authorized_view"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GetAuthorizedView", request_serializer=bigtable_table_admin.GetAuthorizedViewRequest.serialize, response_deserializer=table.AuthorizedView.deserialize, @@ -588,7 +675,7 @@ def update_authorized_view( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_authorized_view" not in self._stubs: - self._stubs["update_authorized_view"] = self.grpc_channel.unary_unary( + self._stubs["update_authorized_view"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/UpdateAuthorizedView", request_serializer=bigtable_table_admin.UpdateAuthorizedViewRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -616,7 +703,7 @@ def delete_authorized_view( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_authorized_view" not in self._stubs: - self._stubs["delete_authorized_view"] = self.grpc_channel.unary_unary( + self._stubs["delete_authorized_view"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/DeleteAuthorizedView", request_serializer=bigtable_table_admin.DeleteAuthorizedViewRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -648,7 +735,7 @@ def modify_column_families( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "modify_column_families" not in self._stubs: - self._stubs["modify_column_families"] = self.grpc_channel.unary_unary( + self._stubs["modify_column_families"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/ModifyColumnFamilies", request_serializer=bigtable_table_admin.ModifyColumnFamiliesRequest.serialize, response_deserializer=table.Table.deserialize, @@ -679,7 +766,7 @@ def drop_row_range( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "drop_row_range" not in self._stubs: - self._stubs["drop_row_range"] = self.grpc_channel.unary_unary( + self._stubs["drop_row_range"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/DropRowRange", request_serializer=bigtable_table_admin.DropRowRangeRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -712,7 +799,9 @@ def generate_consistency_token( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "generate_consistency_token" not in self._stubs: - self._stubs["generate_consistency_token"] = self.grpc_channel.unary_unary( + self._stubs[ + "generate_consistency_token" + ] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GenerateConsistencyToken", request_serializer=bigtable_table_admin.GenerateConsistencyTokenRequest.serialize, response_deserializer=bigtable_table_admin.GenerateConsistencyTokenResponse.deserialize, @@ -744,7 +833,7 @@ def check_consistency( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "check_consistency" not in self._stubs: - self._stubs["check_consistency"] = self.grpc_channel.unary_unary( + self._stubs["check_consistency"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CheckConsistency", request_serializer=bigtable_table_admin.CheckConsistencyRequest.serialize, response_deserializer=bigtable_table_admin.CheckConsistencyResponse.deserialize, @@ -781,7 +870,7 @@ def snapshot_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "snapshot_table" not in self._stubs: - self._stubs["snapshot_table"] = self.grpc_channel.unary_unary( + self._stubs["snapshot_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/SnapshotTable", request_serializer=bigtable_table_admin.SnapshotTableRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -814,7 +903,7 @@ def get_snapshot( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_snapshot" not in self._stubs: - self._stubs["get_snapshot"] = self.grpc_channel.unary_unary( + self._stubs["get_snapshot"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GetSnapshot", request_serializer=bigtable_table_admin.GetSnapshotRequest.serialize, response_deserializer=table.Snapshot.deserialize, @@ -850,7 +939,7 @@ def list_snapshots( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_snapshots" not in self._stubs: - self._stubs["list_snapshots"] = self.grpc_channel.unary_unary( + self._stubs["list_snapshots"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/ListSnapshots", request_serializer=bigtable_table_admin.ListSnapshotsRequest.serialize, response_deserializer=bigtable_table_admin.ListSnapshotsResponse.deserialize, @@ -885,7 +974,7 @@ def delete_snapshot( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_snapshot" not in self._stubs: - self._stubs["delete_snapshot"] = self.grpc_channel.unary_unary( + self._stubs["delete_snapshot"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/DeleteSnapshot", request_serializer=bigtable_table_admin.DeleteSnapshotRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -921,7 +1010,7 @@ def create_backup( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_backup" not in self._stubs: - self._stubs["create_backup"] = self.grpc_channel.unary_unary( + self._stubs["create_backup"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CreateBackup", request_serializer=bigtable_table_admin.CreateBackupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -948,7 +1037,7 @@ def get_backup( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_backup" not in self._stubs: - self._stubs["get_backup"] = self.grpc_channel.unary_unary( + self._stubs["get_backup"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GetBackup", request_serializer=bigtable_table_admin.GetBackupRequest.serialize, response_deserializer=table.Backup.deserialize, @@ -974,7 +1063,7 @@ def update_backup( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_backup" not in self._stubs: - self._stubs["update_backup"] = self.grpc_channel.unary_unary( + self._stubs["update_backup"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/UpdateBackup", request_serializer=bigtable_table_admin.UpdateBackupRequest.serialize, response_deserializer=table.Backup.deserialize, @@ -1002,7 +1091,7 @@ def delete_backup( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_backup" not in self._stubs: - self._stubs["delete_backup"] = self.grpc_channel.unary_unary( + self._stubs["delete_backup"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/DeleteBackup", request_serializer=bigtable_table_admin.DeleteBackupRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -1032,7 +1121,7 @@ def list_backups( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_backups" not in self._stubs: - self._stubs["list_backups"] = self.grpc_channel.unary_unary( + self._stubs["list_backups"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/ListBackups", request_serializer=bigtable_table_admin.ListBackupsRequest.serialize, response_deserializer=bigtable_table_admin.ListBackupsResponse.deserialize, @@ -1067,7 +1156,7 @@ def restore_table( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "restore_table" not in self._stubs: - self._stubs["restore_table"] = self.grpc_channel.unary_unary( + self._stubs["restore_table"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/RestoreTable", request_serializer=bigtable_table_admin.RestoreTableRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -1097,7 +1186,7 @@ def copy_backup( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "copy_backup" not in self._stubs: - self._stubs["copy_backup"] = self.grpc_channel.unary_unary( + self._stubs["copy_backup"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/CopyBackup", request_serializer=bigtable_table_admin.CopyBackupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -1125,7 +1214,7 @@ def get_iam_policy( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/GetIamPolicy", request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -1152,7 +1241,7 @@ def set_iam_policy( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/SetIamPolicy", request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -1182,7 +1271,7 @@ def test_iam_permissions( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( "/google.bigtable.admin.v2.BigtableTableAdmin/TestIamPermissions", request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, @@ -1307,9 +1396,9 @@ def _prep_wrapped_messages(self, client_info): core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), - deadline=60.0, + deadline=3600.0, ), - default_timeout=60.0, + default_timeout=3600.0, client_info=client_info, ), self.snapshot_table: self._wrap_method( @@ -1450,7 +1539,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/rest.py b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/rest.py index b25ddec60..80d485bd0 100644 --- a/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/rest.py +++ b/google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/rest.py @@ -13,9 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import logging +import json # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries @@ -49,6 +50,14 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -301,8 +310,11 @@ def post_update_table(self, response): def pre_check_consistency( self, request: bigtable_table_admin.CheckConsistencyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.CheckConsistencyRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.CheckConsistencyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for check_consistency Override in a subclass to manipulate the request or metadata @@ -315,17 +327,45 @@ def post_check_consistency( ) -> bigtable_table_admin.CheckConsistencyResponse: """Post-rpc interceptor for check_consistency - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_check_consistency_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_check_consistency` interceptor runs + before the `post_check_consistency_with_metadata` interceptor. """ return response + def post_check_consistency_with_metadata( + self, + response: bigtable_table_admin.CheckConsistencyResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.CheckConsistencyResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for check_consistency + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_check_consistency_with_metadata` + interceptor in new development instead of the `post_check_consistency` interceptor. + When both interceptors are used, this `post_check_consistency_with_metadata` interceptor runs after the + `post_check_consistency` interceptor. The (possibly modified) response returned by + `post_check_consistency` will be passed to + `post_check_consistency_with_metadata`. + """ + return response, metadata + def pre_copy_backup( self, request: bigtable_table_admin.CopyBackupRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.CopyBackupRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.CopyBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for copy_backup Override in a subclass to manipulate the request or metadata @@ -338,18 +378,42 @@ def post_copy_backup( ) -> operations_pb2.Operation: """Post-rpc interceptor for copy_backup - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_copy_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_copy_backup` interceptor runs + before the `post_copy_backup_with_metadata` interceptor. """ return response + def post_copy_backup_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for copy_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_copy_backup_with_metadata` + interceptor in new development instead of the `post_copy_backup` interceptor. + When both interceptors are used, this `post_copy_backup_with_metadata` interceptor runs after the + `post_copy_backup` interceptor. The (possibly modified) response returned by + `post_copy_backup` will be passed to + `post_copy_backup_with_metadata`. + """ + return response, metadata + def pre_create_authorized_view( self, request: bigtable_table_admin.CreateAuthorizedViewRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_table_admin.CreateAuthorizedViewRequest, Sequence[Tuple[str, str]] + bigtable_table_admin.CreateAuthorizedViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for create_authorized_view @@ -363,17 +427,43 @@ def post_create_authorized_view( ) -> operations_pb2.Operation: """Post-rpc interceptor for create_authorized_view - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_create_authorized_view_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_create_authorized_view` interceptor runs + before the `post_create_authorized_view_with_metadata` interceptor. """ return response + def post_create_authorized_view_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_authorized_view + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_create_authorized_view_with_metadata` + interceptor in new development instead of the `post_create_authorized_view` interceptor. + When both interceptors are used, this `post_create_authorized_view_with_metadata` interceptor runs after the + `post_create_authorized_view` interceptor. The (possibly modified) response returned by + `post_create_authorized_view` will be passed to + `post_create_authorized_view_with_metadata`. + """ + return response, metadata + def pre_create_backup( self, request: bigtable_table_admin.CreateBackupRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.CreateBackupRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.CreateBackupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_backup Override in a subclass to manipulate the request or metadata @@ -386,17 +476,42 @@ def post_create_backup( ) -> operations_pb2.Operation: """Post-rpc interceptor for create_backup - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_create_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_create_backup` interceptor runs + before the `post_create_backup_with_metadata` interceptor. """ return response + def post_create_backup_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_create_backup_with_metadata` + interceptor in new development instead of the `post_create_backup` interceptor. + When both interceptors are used, this `post_create_backup_with_metadata` interceptor runs after the + `post_create_backup` interceptor. The (possibly modified) response returned by + `post_create_backup` will be passed to + `post_create_backup_with_metadata`. + """ + return response, metadata + def pre_create_table( self, request: bigtable_table_admin.CreateTableRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.CreateTableRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.CreateTableRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_table Override in a subclass to manipulate the request or metadata @@ -407,18 +522,42 @@ def pre_create_table( def post_create_table(self, response: gba_table.Table) -> gba_table.Table: """Post-rpc interceptor for create_table - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_create_table_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_create_table` interceptor runs + before the `post_create_table_with_metadata` interceptor. """ return response + def post_create_table_with_metadata( + self, + response: gba_table.Table, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gba_table.Table, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_table + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_create_table_with_metadata` + interceptor in new development instead of the `post_create_table` interceptor. + When both interceptors are used, this `post_create_table_with_metadata` interceptor runs after the + `post_create_table` interceptor. The (possibly modified) response returned by + `post_create_table` will be passed to + `post_create_table_with_metadata`. + """ + return response, metadata + def pre_create_table_from_snapshot( self, request: bigtable_table_admin.CreateTableFromSnapshotRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_table_admin.CreateTableFromSnapshotRequest, Sequence[Tuple[str, str]] + bigtable_table_admin.CreateTableFromSnapshotRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for create_table_from_snapshot @@ -432,18 +571,42 @@ def post_create_table_from_snapshot( ) -> operations_pb2.Operation: """Post-rpc interceptor for create_table_from_snapshot - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_create_table_from_snapshot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_create_table_from_snapshot` interceptor runs + before the `post_create_table_from_snapshot_with_metadata` interceptor. """ return response + def post_create_table_from_snapshot_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_table_from_snapshot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_create_table_from_snapshot_with_metadata` + interceptor in new development instead of the `post_create_table_from_snapshot` interceptor. + When both interceptors are used, this `post_create_table_from_snapshot_with_metadata` interceptor runs after the + `post_create_table_from_snapshot` interceptor. The (possibly modified) response returned by + `post_create_table_from_snapshot` will be passed to + `post_create_table_from_snapshot_with_metadata`. + """ + return response, metadata + def pre_delete_authorized_view( self, request: bigtable_table_admin.DeleteAuthorizedViewRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_table_admin.DeleteAuthorizedViewRequest, Sequence[Tuple[str, str]] + bigtable_table_admin.DeleteAuthorizedViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for delete_authorized_view @@ -455,8 +618,11 @@ def pre_delete_authorized_view( def pre_delete_backup( self, request: bigtable_table_admin.DeleteBackupRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.DeleteBackupRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.DeleteBackupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for delete_backup Override in a subclass to manipulate the request or metadata @@ -467,8 +633,11 @@ def pre_delete_backup( def pre_delete_snapshot( self, request: bigtable_table_admin.DeleteSnapshotRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.DeleteSnapshotRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.DeleteSnapshotRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for delete_snapshot Override in a subclass to manipulate the request or metadata @@ -479,8 +648,10 @@ def pre_delete_snapshot( def pre_delete_table( self, request: bigtable_table_admin.DeleteTableRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.DeleteTableRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.DeleteTableRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_table Override in a subclass to manipulate the request or metadata @@ -491,8 +662,11 @@ def pre_delete_table( def pre_drop_row_range( self, request: bigtable_table_admin.DropRowRangeRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.DropRowRangeRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.DropRowRangeRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for drop_row_range Override in a subclass to manipulate the request or metadata @@ -503,9 +677,10 @@ def pre_drop_row_range( def pre_generate_consistency_token( self, request: bigtable_table_admin.GenerateConsistencyTokenRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_table_admin.GenerateConsistencyTokenRequest, Sequence[Tuple[str, str]] + bigtable_table_admin.GenerateConsistencyTokenRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for generate_consistency_token @@ -519,18 +694,45 @@ def post_generate_consistency_token( ) -> bigtable_table_admin.GenerateConsistencyTokenResponse: """Post-rpc interceptor for generate_consistency_token - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_generate_consistency_token_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_generate_consistency_token` interceptor runs + before the `post_generate_consistency_token_with_metadata` interceptor. """ return response + def post_generate_consistency_token_with_metadata( + self, + response: bigtable_table_admin.GenerateConsistencyTokenResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.GenerateConsistencyTokenResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for generate_consistency_token + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_generate_consistency_token_with_metadata` + interceptor in new development instead of the `post_generate_consistency_token` interceptor. + When both interceptors are used, this `post_generate_consistency_token_with_metadata` interceptor runs after the + `post_generate_consistency_token` interceptor. The (possibly modified) response returned by + `post_generate_consistency_token` will be passed to + `post_generate_consistency_token_with_metadata`. + """ + return response, metadata + def pre_get_authorized_view( self, request: bigtable_table_admin.GetAuthorizedViewRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_table_admin.GetAuthorizedViewRequest, Sequence[Tuple[str, str]] + bigtable_table_admin.GetAuthorizedViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for get_authorized_view @@ -544,17 +746,42 @@ def post_get_authorized_view( ) -> table.AuthorizedView: """Post-rpc interceptor for get_authorized_view - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_authorized_view_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_get_authorized_view` interceptor runs + before the `post_get_authorized_view_with_metadata` interceptor. """ return response + def post_get_authorized_view_with_metadata( + self, + response: table.AuthorizedView, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[table.AuthorizedView, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_authorized_view + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_get_authorized_view_with_metadata` + interceptor in new development instead of the `post_get_authorized_view` interceptor. + When both interceptors are used, this `post_get_authorized_view_with_metadata` interceptor runs after the + `post_get_authorized_view` interceptor. The (possibly modified) response returned by + `post_get_authorized_view` will be passed to + `post_get_authorized_view_with_metadata`. + """ + return response, metadata + def pre_get_backup( self, request: bigtable_table_admin.GetBackupRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.GetBackupRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.GetBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_backup Override in a subclass to manipulate the request or metadata @@ -565,17 +792,40 @@ def pre_get_backup( def post_get_backup(self, response: table.Backup) -> table.Backup: """Post-rpc interceptor for get_backup - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_get_backup` interceptor runs + before the `post_get_backup_with_metadata` interceptor. """ return response + def post_get_backup_with_metadata( + self, response: table.Backup, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[table.Backup, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_get_backup_with_metadata` + interceptor in new development instead of the `post_get_backup` interceptor. + When both interceptors are used, this `post_get_backup_with_metadata` interceptor runs after the + `post_get_backup` interceptor. The (possibly modified) response returned by + `post_get_backup` will be passed to + `post_get_backup_with_metadata`. + """ + return response, metadata + def pre_get_iam_policy( self, request: iam_policy_pb2.GetIamPolicyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_iam_policy Override in a subclass to manipulate the request or metadata @@ -586,17 +836,42 @@ def pre_get_iam_policy( def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for get_iam_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_iam_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_get_iam_policy` interceptor runs + before the `post_get_iam_policy_with_metadata` interceptor. """ return response + def post_get_iam_policy_with_metadata( + self, + response: policy_pb2.Policy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[policy_pb2.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_get_iam_policy_with_metadata` + interceptor in new development instead of the `post_get_iam_policy` interceptor. + When both interceptors are used, this `post_get_iam_policy_with_metadata` interceptor runs after the + `post_get_iam_policy` interceptor. The (possibly modified) response returned by + `post_get_iam_policy` will be passed to + `post_get_iam_policy_with_metadata`. + """ + return response, metadata + def pre_get_snapshot( self, request: bigtable_table_admin.GetSnapshotRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.GetSnapshotRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.GetSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_snapshot Override in a subclass to manipulate the request or metadata @@ -607,17 +882,42 @@ def pre_get_snapshot( def post_get_snapshot(self, response: table.Snapshot) -> table.Snapshot: """Post-rpc interceptor for get_snapshot - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_snapshot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_get_snapshot` interceptor runs + before the `post_get_snapshot_with_metadata` interceptor. """ return response + def post_get_snapshot_with_metadata( + self, + response: table.Snapshot, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[table.Snapshot, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_snapshot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_get_snapshot_with_metadata` + interceptor in new development instead of the `post_get_snapshot` interceptor. + When both interceptors are used, this `post_get_snapshot_with_metadata` interceptor runs after the + `post_get_snapshot` interceptor. The (possibly modified) response returned by + `post_get_snapshot` will be passed to + `post_get_snapshot_with_metadata`. + """ + return response, metadata + def pre_get_table( self, request: bigtable_table_admin.GetTableRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.GetTableRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.GetTableRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_table Override in a subclass to manipulate the request or metadata @@ -628,18 +928,40 @@ def pre_get_table( def post_get_table(self, response: table.Table) -> table.Table: """Post-rpc interceptor for get_table - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_table_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_get_table` interceptor runs + before the `post_get_table_with_metadata` interceptor. """ return response + def post_get_table_with_metadata( + self, response: table.Table, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[table.Table, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_table + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_get_table_with_metadata` + interceptor in new development instead of the `post_get_table` interceptor. + When both interceptors are used, this `post_get_table_with_metadata` interceptor runs after the + `post_get_table` interceptor. The (possibly modified) response returned by + `post_get_table` will be passed to + `post_get_table_with_metadata`. + """ + return response, metadata + def pre_list_authorized_views( self, request: bigtable_table_admin.ListAuthorizedViewsRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_table_admin.ListAuthorizedViewsRequest, Sequence[Tuple[str, str]] + bigtable_table_admin.ListAuthorizedViewsRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for list_authorized_views @@ -653,17 +975,45 @@ def post_list_authorized_views( ) -> bigtable_table_admin.ListAuthorizedViewsResponse: """Post-rpc interceptor for list_authorized_views - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_authorized_views_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_list_authorized_views` interceptor runs + before the `post_list_authorized_views_with_metadata` interceptor. """ return response + def post_list_authorized_views_with_metadata( + self, + response: bigtable_table_admin.ListAuthorizedViewsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.ListAuthorizedViewsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_authorized_views + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_list_authorized_views_with_metadata` + interceptor in new development instead of the `post_list_authorized_views` interceptor. + When both interceptors are used, this `post_list_authorized_views_with_metadata` interceptor runs after the + `post_list_authorized_views` interceptor. The (possibly modified) response returned by + `post_list_authorized_views` will be passed to + `post_list_authorized_views_with_metadata`. + """ + return response, metadata + def pre_list_backups( self, request: bigtable_table_admin.ListBackupsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.ListBackupsRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.ListBackupsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_backups Override in a subclass to manipulate the request or metadata @@ -676,17 +1026,46 @@ def post_list_backups( ) -> bigtable_table_admin.ListBackupsResponse: """Post-rpc interceptor for list_backups - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_backups_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_list_backups` interceptor runs + before the `post_list_backups_with_metadata` interceptor. """ return response + def post_list_backups_with_metadata( + self, + response: bigtable_table_admin.ListBackupsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.ListBackupsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_backups + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_list_backups_with_metadata` + interceptor in new development instead of the `post_list_backups` interceptor. + When both interceptors are used, this `post_list_backups_with_metadata` interceptor runs after the + `post_list_backups` interceptor. The (possibly modified) response returned by + `post_list_backups` will be passed to + `post_list_backups_with_metadata`. + """ + return response, metadata + def pre_list_snapshots( self, request: bigtable_table_admin.ListSnapshotsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.ListSnapshotsRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.ListSnapshotsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_snapshots Override in a subclass to manipulate the request or metadata @@ -699,17 +1078,45 @@ def post_list_snapshots( ) -> bigtable_table_admin.ListSnapshotsResponse: """Post-rpc interceptor for list_snapshots - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_snapshots_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_list_snapshots` interceptor runs + before the `post_list_snapshots_with_metadata` interceptor. """ return response + def post_list_snapshots_with_metadata( + self, + response: bigtable_table_admin.ListSnapshotsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.ListSnapshotsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_snapshots + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_list_snapshots_with_metadata` + interceptor in new development instead of the `post_list_snapshots` interceptor. + When both interceptors are used, this `post_list_snapshots_with_metadata` interceptor runs after the + `post_list_snapshots` interceptor. The (possibly modified) response returned by + `post_list_snapshots` will be passed to + `post_list_snapshots_with_metadata`. + """ + return response, metadata + def pre_list_tables( self, request: bigtable_table_admin.ListTablesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.ListTablesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.ListTablesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_tables Override in a subclass to manipulate the request or metadata @@ -722,18 +1129,44 @@ def post_list_tables( ) -> bigtable_table_admin.ListTablesResponse: """Post-rpc interceptor for list_tables - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_tables_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_list_tables` interceptor runs + before the `post_list_tables_with_metadata` interceptor. """ return response + def post_list_tables_with_metadata( + self, + response: bigtable_table_admin.ListTablesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.ListTablesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_tables + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_list_tables_with_metadata` + interceptor in new development instead of the `post_list_tables` interceptor. + When both interceptors are used, this `post_list_tables_with_metadata` interceptor runs after the + `post_list_tables` interceptor. The (possibly modified) response returned by + `post_list_tables` will be passed to + `post_list_tables_with_metadata`. + """ + return response, metadata + def pre_modify_column_families( self, request: bigtable_table_admin.ModifyColumnFamiliesRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_table_admin.ModifyColumnFamiliesRequest, Sequence[Tuple[str, str]] + bigtable_table_admin.ModifyColumnFamiliesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for modify_column_families @@ -745,17 +1178,41 @@ def pre_modify_column_families( def post_modify_column_families(self, response: table.Table) -> table.Table: """Post-rpc interceptor for modify_column_families - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_modify_column_families_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_modify_column_families` interceptor runs + before the `post_modify_column_families_with_metadata` interceptor. """ return response + def post_modify_column_families_with_metadata( + self, response: table.Table, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[table.Table, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for modify_column_families + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_modify_column_families_with_metadata` + interceptor in new development instead of the `post_modify_column_families` interceptor. + When both interceptors are used, this `post_modify_column_families_with_metadata` interceptor runs after the + `post_modify_column_families` interceptor. The (possibly modified) response returned by + `post_modify_column_families` will be passed to + `post_modify_column_families_with_metadata`. + """ + return response, metadata + def pre_restore_table( self, request: bigtable_table_admin.RestoreTableRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.RestoreTableRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.RestoreTableRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for restore_table Override in a subclass to manipulate the request or metadata @@ -768,17 +1225,42 @@ def post_restore_table( ) -> operations_pb2.Operation: """Post-rpc interceptor for restore_table - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_restore_table_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_restore_table` interceptor runs + before the `post_restore_table_with_metadata` interceptor. """ return response + def post_restore_table_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for restore_table + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_restore_table_with_metadata` + interceptor in new development instead of the `post_restore_table` interceptor. + When both interceptors are used, this `post_restore_table_with_metadata` interceptor runs after the + `post_restore_table` interceptor. The (possibly modified) response returned by + `post_restore_table` will be passed to + `post_restore_table_with_metadata`. + """ + return response, metadata + def pre_set_iam_policy( self, request: iam_policy_pb2.SetIamPolicyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for set_iam_policy Override in a subclass to manipulate the request or metadata @@ -789,17 +1271,43 @@ def pre_set_iam_policy( def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for set_iam_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_set_iam_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_set_iam_policy` interceptor runs + before the `post_set_iam_policy_with_metadata` interceptor. """ return response + def post_set_iam_policy_with_metadata( + self, + response: policy_pb2.Policy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[policy_pb2.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_set_iam_policy_with_metadata` + interceptor in new development instead of the `post_set_iam_policy` interceptor. + When both interceptors are used, this `post_set_iam_policy_with_metadata` interceptor runs after the + `post_set_iam_policy` interceptor. The (possibly modified) response returned by + `post_set_iam_policy` will be passed to + `post_set_iam_policy_with_metadata`. + """ + return response, metadata + def pre_snapshot_table( self, request: bigtable_table_admin.SnapshotTableRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.SnapshotTableRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.SnapshotTableRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for snapshot_table Override in a subclass to manipulate the request or metadata @@ -812,17 +1320,43 @@ def post_snapshot_table( ) -> operations_pb2.Operation: """Post-rpc interceptor for snapshot_table - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_snapshot_table_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_snapshot_table` interceptor runs + before the `post_snapshot_table_with_metadata` interceptor. """ return response + def post_snapshot_table_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for snapshot_table + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_snapshot_table_with_metadata` + interceptor in new development instead of the `post_snapshot_table` interceptor. + When both interceptors are used, this `post_snapshot_table_with_metadata` interceptor runs after the + `post_snapshot_table` interceptor. The (possibly modified) response returned by + `post_snapshot_table` will be passed to + `post_snapshot_table_with_metadata`. + """ + return response, metadata + def pre_test_iam_permissions( self, request: iam_policy_pb2.TestIamPermissionsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for test_iam_permissions Override in a subclass to manipulate the request or metadata @@ -835,17 +1369,46 @@ def post_test_iam_permissions( ) -> iam_policy_pb2.TestIamPermissionsResponse: """Post-rpc interceptor for test_iam_permissions - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_test_iam_permissions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_test_iam_permissions` interceptor runs + before the `post_test_iam_permissions_with_metadata` interceptor. """ return response + def post_test_iam_permissions_with_metadata( + self, + response: iam_policy_pb2.TestIamPermissionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_test_iam_permissions_with_metadata` + interceptor in new development instead of the `post_test_iam_permissions` interceptor. + When both interceptors are used, this `post_test_iam_permissions_with_metadata` interceptor runs after the + `post_test_iam_permissions` interceptor. The (possibly modified) response returned by + `post_test_iam_permissions` will be passed to + `post_test_iam_permissions_with_metadata`. + """ + return response, metadata + def pre_undelete_table( self, request: bigtable_table_admin.UndeleteTableRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.UndeleteTableRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.UndeleteTableRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for undelete_table Override in a subclass to manipulate the request or metadata @@ -858,18 +1421,42 @@ def post_undelete_table( ) -> operations_pb2.Operation: """Post-rpc interceptor for undelete_table - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_undelete_table_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_undelete_table` interceptor runs + before the `post_undelete_table_with_metadata` interceptor. """ return response + def post_undelete_table_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for undelete_table + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_undelete_table_with_metadata` + interceptor in new development instead of the `post_undelete_table` interceptor. + When both interceptors are used, this `post_undelete_table_with_metadata` interceptor runs after the + `post_undelete_table` interceptor. The (possibly modified) response returned by + `post_undelete_table` will be passed to + `post_undelete_table_with_metadata`. + """ + return response, metadata + def pre_update_authorized_view( self, request: bigtable_table_admin.UpdateAuthorizedViewRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable_table_admin.UpdateAuthorizedViewRequest, Sequence[Tuple[str, str]] + bigtable_table_admin.UpdateAuthorizedViewRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_authorized_view @@ -883,17 +1470,43 @@ def post_update_authorized_view( ) -> operations_pb2.Operation: """Post-rpc interceptor for update_authorized_view - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_update_authorized_view_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_update_authorized_view` interceptor runs + before the `post_update_authorized_view_with_metadata` interceptor. """ return response + def post_update_authorized_view_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_authorized_view + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_update_authorized_view_with_metadata` + interceptor in new development instead of the `post_update_authorized_view` interceptor. + When both interceptors are used, this `post_update_authorized_view_with_metadata` interceptor runs after the + `post_update_authorized_view` interceptor. The (possibly modified) response returned by + `post_update_authorized_view` will be passed to + `post_update_authorized_view_with_metadata`. + """ + return response, metadata + def pre_update_backup( self, request: bigtable_table_admin.UpdateBackupRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.UpdateBackupRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.UpdateBackupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_backup Override in a subclass to manipulate the request or metadata @@ -904,17 +1517,40 @@ def pre_update_backup( def post_update_backup(self, response: table.Backup) -> table.Backup: """Post-rpc interceptor for update_backup - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_update_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_update_backup` interceptor runs + before the `post_update_backup_with_metadata` interceptor. """ return response + def post_update_backup_with_metadata( + self, response: table.Backup, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[table.Backup, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_update_backup_with_metadata` + interceptor in new development instead of the `post_update_backup` interceptor. + When both interceptors are used, this `post_update_backup_with_metadata` interceptor runs after the + `post_update_backup` interceptor. The (possibly modified) response returned by + `post_update_backup` will be passed to + `post_update_backup_with_metadata`. + """ + return response, metadata + def pre_update_table( self, request: bigtable_table_admin.UpdateTableRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable_table_admin.UpdateTableRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_table_admin.UpdateTableRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_table Override in a subclass to manipulate the request or metadata @@ -927,12 +1563,35 @@ def post_update_table( ) -> operations_pb2.Operation: """Post-rpc interceptor for update_table - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_update_table_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BigtableTableAdmin server but before - it is returned to user code. + it is returned to user code. This `post_update_table` interceptor runs + before the `post_update_table_with_metadata` interceptor. """ return response + def post_update_table_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_table + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableTableAdmin server but before it is returned to user code. + + We recommend only using this `post_update_table_with_metadata` + interceptor in new development instead of the `post_update_table` interceptor. + When both interceptors are used, this `post_update_table_with_metadata` interceptor runs after the + `post_update_table` interceptor. The (possibly modified) response returned by + `post_update_table` will be passed to + `post_update_table_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class BigtableTableAdminRestStub: @@ -1113,7 +1772,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_table_admin.CheckConsistencyResponse: r"""Call the check consistency method over HTTP. @@ -1124,8 +1783,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable_table_admin.CheckConsistencyResponse: @@ -1137,6 +1798,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseCheckConsistency._get_http_options() ) + request, metadata = self._interceptor.pre_check_consistency( request, metadata ) @@ -1153,6 +1815,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.CheckConsistency", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CheckConsistency", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._CheckConsistency._get_response( self._host, @@ -1174,7 +1863,35 @@ def __call__( pb_resp = bigtable_table_admin.CheckConsistencyResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_check_consistency(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_check_consistency_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_table_admin.CheckConsistencyResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.check_consistency", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CheckConsistency", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CopyBackup( @@ -1212,7 +1929,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the copy backup method over HTTP. @@ -1223,8 +1940,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1237,6 +1956,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseCopyBackup._get_http_options() ) + request, metadata = self._interceptor.pre_copy_backup(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseCopyBackup._get_transcoded_request( http_options, request @@ -1251,6 +1971,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.CopyBackup", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CopyBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._CopyBackup._get_response( self._host, @@ -1270,7 +2017,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_copy_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_copy_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.copy_backup", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CopyBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CreateAuthorizedView( @@ -1309,7 +2082,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the create authorized view method over HTTP. @@ -1320,8 +2093,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1334,6 +2109,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseCreateAuthorizedView._get_http_options() ) + request, metadata = self._interceptor.pre_create_authorized_view( request, metadata ) @@ -1350,6 +2126,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.CreateAuthorizedView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CreateAuthorizedView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableTableAdminRestTransport._CreateAuthorizedView._get_response( @@ -1371,7 +2174,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_authorized_view(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_authorized_view_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.create_authorized_view", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CreateAuthorizedView", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CreateBackup( @@ -1410,7 +2239,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the create backup method over HTTP. @@ -1421,8 +2250,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1435,6 +2266,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseCreateBackup._get_http_options() ) + request, metadata = self._interceptor.pre_create_backup(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseCreateBackup._get_transcoded_request( http_options, request @@ -1449,6 +2281,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.CreateBackup", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CreateBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._CreateBackup._get_response( self._host, @@ -1468,7 +2327,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.create_backup", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CreateBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CreateTable( @@ -1507,7 +2392,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> gba_table.Table: r"""Call the create table method over HTTP. @@ -1518,8 +2403,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.gba_table.Table: @@ -1533,6 +2420,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseCreateTable._get_http_options() ) + request, metadata = self._interceptor.pre_create_table(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseCreateTable._get_transcoded_request( http_options, request @@ -1547,6 +2435,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.CreateTable", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CreateTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._CreateTable._get_response( self._host, @@ -1568,7 +2483,33 @@ def __call__( pb_resp = gba_table.Table.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_table(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_table_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gba_table.Table.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.create_table", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CreateTable", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CreateTableFromSnapshot( @@ -1607,7 +2548,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the create table from snapshot method over HTTP. @@ -1626,8 +2567,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1640,6 +2583,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseCreateTableFromSnapshot._get_http_options() ) + request, metadata = self._interceptor.pre_create_table_from_snapshot( request, metadata ) @@ -1656,6 +2600,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.CreateTableFromSnapshot", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CreateTableFromSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableTableAdminRestTransport._CreateTableFromSnapshot._get_response( @@ -1677,7 +2648,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_table_from_snapshot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_table_from_snapshot_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.create_table_from_snapshot", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "CreateTableFromSnapshot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _DeleteAuthorizedView( @@ -1715,7 +2712,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete authorized view method over HTTP. @@ -1726,13 +2723,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ http_options = ( _BaseBigtableTableAdminRestTransport._BaseDeleteAuthorizedView._get_http_options() ) + request, metadata = self._interceptor.pre_delete_authorized_view( request, metadata ) @@ -1745,6 +2745,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.DeleteAuthorizedView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "DeleteAuthorizedView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableTableAdminRestTransport._DeleteAuthorizedView._get_response( @@ -1797,7 +2824,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete backup method over HTTP. @@ -1808,13 +2835,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ http_options = ( _BaseBigtableTableAdminRestTransport._BaseDeleteBackup._get_http_options() ) + request, metadata = self._interceptor.pre_delete_backup(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseDeleteBackup._get_transcoded_request( http_options, request @@ -1825,6 +2855,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.DeleteBackup", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "DeleteBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._DeleteBackup._get_response( self._host, @@ -1875,7 +2932,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete snapshot method over HTTP. @@ -1893,13 +2950,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ http_options = ( _BaseBigtableTableAdminRestTransport._BaseDeleteSnapshot._get_http_options() ) + request, metadata = self._interceptor.pre_delete_snapshot(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseDeleteSnapshot._get_transcoded_request( http_options, request @@ -1910,6 +2970,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.DeleteSnapshot", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "DeleteSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._DeleteSnapshot._get_response( self._host, @@ -1960,7 +3047,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the delete table method over HTTP. @@ -1971,13 +3058,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ http_options = ( _BaseBigtableTableAdminRestTransport._BaseDeleteTable._get_http_options() ) + request, metadata = self._interceptor.pre_delete_table(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseDeleteTable._get_transcoded_request( http_options, request @@ -1988,6 +3078,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.DeleteTable", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "DeleteTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._DeleteTable._get_response( self._host, @@ -2039,7 +3156,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ): r"""Call the drop row range method over HTTP. @@ -2050,13 +3167,16 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ http_options = ( _BaseBigtableTableAdminRestTransport._BaseDropRowRange._get_http_options() ) + request, metadata = self._interceptor.pre_drop_row_range(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseDropRowRange._get_transcoded_request( http_options, request @@ -2071,6 +3191,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.DropRowRange", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "DropRowRange", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._DropRowRange._get_response( self._host, @@ -2123,7 +3270,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_table_admin.GenerateConsistencyTokenResponse: r"""Call the generate consistency token method over HTTP. @@ -2135,8 +3282,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable_table_admin.GenerateConsistencyTokenResponse: @@ -2148,6 +3297,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseGenerateConsistencyToken._get_http_options() ) + request, metadata = self._interceptor.pre_generate_consistency_token( request, metadata ) @@ -2164,6 +3314,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.GenerateConsistencyToken", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GenerateConsistencyToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableTableAdminRestTransport._GenerateConsistencyToken._get_response( @@ -2187,7 +3364,37 @@ def __call__( pb_resp = bigtable_table_admin.GenerateConsistencyTokenResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_consistency_token(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_generate_consistency_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_table_admin.GenerateConsistencyTokenResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.generate_consistency_token", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GenerateConsistencyToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetAuthorizedView( @@ -2225,7 +3432,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.AuthorizedView: r"""Call the get authorized view method over HTTP. @@ -2236,8 +3443,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.table.AuthorizedView: @@ -2253,6 +3462,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseGetAuthorizedView._get_http_options() ) + request, metadata = self._interceptor.pre_get_authorized_view( request, metadata ) @@ -2265,6 +3475,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.GetAuthorizedView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GetAuthorizedView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._GetAuthorizedView._get_response( self._host, @@ -2285,7 +3522,33 @@ def __call__( pb_resp = table.AuthorizedView.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_authorized_view(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_authorized_view_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = table.AuthorizedView.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.get_authorized_view", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GetAuthorizedView", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetBackup( @@ -2322,7 +3585,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Backup: r"""Call the get backup method over HTTP. @@ -2333,8 +3596,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.table.Backup: @@ -2344,6 +3609,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseGetBackup._get_http_options() ) + request, metadata = self._interceptor.pre_get_backup(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseGetBackup._get_transcoded_request( http_options, request @@ -2354,6 +3620,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.GetBackup", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GetBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._GetBackup._get_response( self._host, @@ -2374,7 +3667,33 @@ def __call__( pb_resp = table.Backup.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = table.Backup.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.get_backup", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GetBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetIamPolicy( @@ -2413,7 +3732,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Call the get iam policy method over HTTP. @@ -2423,8 +3742,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.policy_pb2.Policy: @@ -2509,6 +3830,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseGetIamPolicy._get_http_options() ) + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseGetIamPolicy._get_transcoded_request( http_options, request @@ -2523,6 +3845,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.GetIamPolicy", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._GetIamPolicy._get_response( self._host, @@ -2544,7 +3893,33 @@ def __call__( pb_resp = resp json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.get_iam_policy", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GetIamPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetSnapshot( @@ -2582,7 +3957,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Snapshot: r"""Call the get snapshot method over HTTP. @@ -2600,8 +3975,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.table.Snapshot: @@ -2624,6 +4001,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseGetSnapshot._get_http_options() ) + request, metadata = self._interceptor.pre_get_snapshot(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseGetSnapshot._get_transcoded_request( http_options, request @@ -2634,6 +4012,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.GetSnapshot", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GetSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._GetSnapshot._get_response( self._host, @@ -2654,7 +4059,33 @@ def __call__( pb_resp = table.Snapshot.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_snapshot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_snapshot_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = table.Snapshot.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.get_snapshot", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GetSnapshot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetTable( @@ -2691,7 +4122,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Table: r"""Call the get table method over HTTP. @@ -2702,8 +4133,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.table.Table: @@ -2717,6 +4150,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseGetTable._get_http_options() ) + request, metadata = self._interceptor.pre_get_table(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseGetTable._get_transcoded_request( http_options, request @@ -2727,6 +4161,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.GetTable", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GetTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._GetTable._get_response( self._host, @@ -2747,7 +4208,33 @@ def __call__( pb_resp = table.Table.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_table(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_table_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = table.Table.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.get_table", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "GetTable", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListAuthorizedViews( @@ -2785,7 +4272,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_table_admin.ListAuthorizedViewsResponse: r"""Call the list authorized views method over HTTP. @@ -2796,8 +4283,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable_table_admin.ListAuthorizedViewsResponse: @@ -2809,6 +4298,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseListAuthorizedViews._get_http_options() ) + request, metadata = self._interceptor.pre_list_authorized_views( request, metadata ) @@ -2821,6 +4311,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.ListAuthorizedViews", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "ListAuthorizedViews", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableTableAdminRestTransport._ListAuthorizedViews._get_response( @@ -2843,7 +4360,37 @@ def __call__( pb_resp = bigtable_table_admin.ListAuthorizedViewsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_authorized_views(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_authorized_views_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_table_admin.ListAuthorizedViewsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.list_authorized_views", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "ListAuthorizedViews", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListBackups( @@ -2881,7 +4428,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_table_admin.ListBackupsResponse: r"""Call the list backups method over HTTP. @@ -2892,8 +4439,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable_table_admin.ListBackupsResponse: @@ -2905,6 +4454,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseListBackups._get_http_options() ) + request, metadata = self._interceptor.pre_list_backups(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseListBackups._get_transcoded_request( http_options, request @@ -2915,6 +4465,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.ListBackups", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "ListBackups", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._ListBackups._get_response( self._host, @@ -2935,7 +4512,35 @@ def __call__( pb_resp = bigtable_table_admin.ListBackupsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_backups(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_backups_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = bigtable_table_admin.ListBackupsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.list_backups", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "ListBackups", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListSnapshots( @@ -2973,7 +4578,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_table_admin.ListSnapshotsResponse: r"""Call the list snapshots method over HTTP. @@ -2991,8 +4596,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable_table_admin.ListSnapshotsResponse: @@ -3011,6 +4618,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseListSnapshots._get_http_options() ) + request, metadata = self._interceptor.pre_list_snapshots(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseListSnapshots._get_transcoded_request( http_options, request @@ -3021,6 +4629,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.ListSnapshots", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "ListSnapshots", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._ListSnapshots._get_response( self._host, @@ -3041,7 +4676,35 @@ def __call__( pb_resp = bigtable_table_admin.ListSnapshotsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_snapshots(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_snapshots_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_table_admin.ListSnapshotsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.list_snapshots", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "ListSnapshots", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListTables( @@ -3078,7 +4741,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable_table_admin.ListTablesResponse: r"""Call the list tables method over HTTP. @@ -3089,8 +4752,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable_table_admin.ListTablesResponse: @@ -3102,6 +4767,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseListTables._get_http_options() ) + request, metadata = self._interceptor.pre_list_tables(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseListTables._get_transcoded_request( http_options, request @@ -3112,6 +4778,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.ListTables", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "ListTables", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._ListTables._get_response( self._host, @@ -3132,7 +4825,35 @@ def __call__( pb_resp = bigtable_table_admin.ListTablesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tables(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_tables_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = bigtable_table_admin.ListTablesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.list_tables", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "ListTables", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ModifyColumnFamilies( @@ -3171,7 +4892,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Table: r"""Call the modify column families method over HTTP. @@ -3182,8 +4903,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.table.Table: @@ -3197,6 +4920,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseModifyColumnFamilies._get_http_options() ) + request, metadata = self._interceptor.pre_modify_column_families( request, metadata ) @@ -3213,6 +4937,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.ModifyColumnFamilies", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "ModifyColumnFamilies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableTableAdminRestTransport._ModifyColumnFamilies._get_response( @@ -3236,7 +4987,33 @@ def __call__( pb_resp = table.Table.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_modify_column_families(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_modify_column_families_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = table.Table.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.modify_column_families", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "ModifyColumnFamilies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _RestoreTable( @@ -3275,7 +5052,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the restore table method over HTTP. @@ -3286,8 +5063,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -3300,6 +5079,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseRestoreTable._get_http_options() ) + request, metadata = self._interceptor.pre_restore_table(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseRestoreTable._get_transcoded_request( http_options, request @@ -3314,6 +5094,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.RestoreTable", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "RestoreTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._RestoreTable._get_response( self._host, @@ -3333,7 +5140,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_restore_table(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_restore_table_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.restore_table", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "RestoreTable", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _SetIamPolicy( @@ -3372,7 +5205,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Call the set iam policy method over HTTP. @@ -3382,8 +5215,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.policy_pb2.Policy: @@ -3468,6 +5303,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseSetIamPolicy._get_http_options() ) + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseSetIamPolicy._get_transcoded_request( http_options, request @@ -3482,6 +5318,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.SetIamPolicy", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._SetIamPolicy._get_response( self._host, @@ -3503,7 +5366,33 @@ def __call__( pb_resp = resp json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_set_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.set_iam_policy", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "SetIamPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _SnapshotTable( @@ -3542,7 +5431,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the snapshot table method over HTTP. @@ -3560,8 +5449,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -3574,6 +5465,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseSnapshotTable._get_http_options() ) + request, metadata = self._interceptor.pre_snapshot_table(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseSnapshotTable._get_transcoded_request( http_options, request @@ -3588,6 +5480,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.SnapshotTable", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "SnapshotTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._SnapshotTable._get_response( self._host, @@ -3607,7 +5526,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_snapshot_table(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_snapshot_table_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.snapshot_table", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "SnapshotTable", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _TestIamPermissions( @@ -3646,7 +5591,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Call the test iam permissions method over HTTP. @@ -3656,8 +5601,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.iam_policy_pb2.TestIamPermissionsResponse: @@ -3667,6 +5614,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseTestIamPermissions._get_http_options() ) + request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) @@ -3683,6 +5631,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.TestIamPermissions", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableTableAdminRestTransport._TestIamPermissions._get_response( @@ -3706,7 +5681,33 @@ def __call__( pb_resp = resp json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_test_iam_permissions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.test_iam_permissions", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "TestIamPermissions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UndeleteTable( @@ -3745,7 +5746,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the undelete table method over HTTP. @@ -3756,8 +5757,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -3770,6 +5773,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseUndeleteTable._get_http_options() ) + request, metadata = self._interceptor.pre_undelete_table(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseUndeleteTable._get_transcoded_request( http_options, request @@ -3784,6 +5788,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.UndeleteTable", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "UndeleteTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._UndeleteTable._get_response( self._host, @@ -3803,7 +5834,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undelete_table(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_undelete_table_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.undelete_table", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "UndeleteTable", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UpdateAuthorizedView( @@ -3842,7 +5899,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the update authorized view method over HTTP. @@ -3853,8 +5910,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -3867,6 +5926,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseUpdateAuthorizedView._get_http_options() ) + request, metadata = self._interceptor.pre_update_authorized_view( request, metadata ) @@ -3883,6 +5943,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.UpdateAuthorizedView", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "UpdateAuthorizedView", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ( BigtableTableAdminRestTransport._UpdateAuthorizedView._get_response( @@ -3904,7 +5991,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_authorized_view(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_authorized_view_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.update_authorized_view", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "UpdateAuthorizedView", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UpdateBackup( @@ -3943,7 +6056,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> table.Backup: r"""Call the update backup method over HTTP. @@ -3954,8 +6067,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.table.Backup: @@ -3965,6 +6080,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseUpdateBackup._get_http_options() ) + request, metadata = self._interceptor.pre_update_backup(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseUpdateBackup._get_transcoded_request( http_options, request @@ -3979,6 +6095,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.UpdateBackup", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "UpdateBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._UpdateBackup._get_response( self._host, @@ -4000,7 +6143,33 @@ def __call__( pb_resp = table.Backup.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = table.Backup.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.update_backup", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "UpdateBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UpdateTable( @@ -4039,7 +6208,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the update table method over HTTP. @@ -4050,8 +6219,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -4064,6 +6235,7 @@ def __call__( http_options = ( _BaseBigtableTableAdminRestTransport._BaseUpdateTable._get_http_options() ) + request, metadata = self._interceptor.pre_update_table(request, metadata) transcoded_request = _BaseBigtableTableAdminRestTransport._BaseUpdateTable._get_transcoded_request( http_options, request @@ -4078,6 +6250,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableTableAdminClient.UpdateTable", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "UpdateTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableTableAdminRestTransport._UpdateTable._get_response( self._host, @@ -4097,7 +6296,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_table(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_table_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableTableAdminClient.update_table", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableTableAdmin", + "rpcName": "UpdateTable", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property diff --git a/google/cloud/bigtable_admin_v2/types/__init__.py b/google/cloud/bigtable_admin_v2/types/__init__.py index 3ff9075d2..817bbc89a 100644 --- a/google/cloud/bigtable_admin_v2/types/__init__.py +++ b/google/cloud/bigtable_admin_v2/types/__init__.py @@ -19,12 +19,20 @@ CreateClusterRequest, CreateInstanceMetadata, CreateInstanceRequest, + CreateLogicalViewMetadata, + CreateLogicalViewRequest, + CreateMaterializedViewMetadata, + CreateMaterializedViewRequest, DeleteAppProfileRequest, DeleteClusterRequest, DeleteInstanceRequest, + DeleteLogicalViewRequest, + DeleteMaterializedViewRequest, GetAppProfileRequest, GetClusterRequest, GetInstanceRequest, + GetLogicalViewRequest, + GetMaterializedViewRequest, ListAppProfilesRequest, ListAppProfilesResponse, ListClustersRequest, @@ -33,6 +41,10 @@ ListHotTabletsResponse, ListInstancesRequest, ListInstancesResponse, + ListLogicalViewsRequest, + ListLogicalViewsResponse, + ListMaterializedViewsRequest, + ListMaterializedViewsResponse, PartialUpdateClusterMetadata, PartialUpdateClusterRequest, PartialUpdateInstanceRequest, @@ -40,6 +52,10 @@ UpdateAppProfileRequest, UpdateClusterMetadata, UpdateInstanceMetadata, + UpdateLogicalViewMetadata, + UpdateLogicalViewRequest, + UpdateMaterializedViewMetadata, + UpdateMaterializedViewRequest, ) from .bigtable_table_admin import ( CheckConsistencyRequest, @@ -99,6 +115,8 @@ Cluster, HotTablet, Instance, + LogicalView, + MaterializedView, ) from .table import ( AuthorizedView, @@ -123,12 +141,20 @@ "CreateClusterRequest", "CreateInstanceMetadata", "CreateInstanceRequest", + "CreateLogicalViewMetadata", + "CreateLogicalViewRequest", + "CreateMaterializedViewMetadata", + "CreateMaterializedViewRequest", "DeleteAppProfileRequest", "DeleteClusterRequest", "DeleteInstanceRequest", + "DeleteLogicalViewRequest", + "DeleteMaterializedViewRequest", "GetAppProfileRequest", "GetClusterRequest", "GetInstanceRequest", + "GetLogicalViewRequest", + "GetMaterializedViewRequest", "ListAppProfilesRequest", "ListAppProfilesResponse", "ListClustersRequest", @@ -137,6 +163,10 @@ "ListHotTabletsResponse", "ListInstancesRequest", "ListInstancesResponse", + "ListLogicalViewsRequest", + "ListLogicalViewsResponse", + "ListMaterializedViewsRequest", + "ListMaterializedViewsResponse", "PartialUpdateClusterMetadata", "PartialUpdateClusterRequest", "PartialUpdateInstanceRequest", @@ -144,6 +174,10 @@ "UpdateAppProfileRequest", "UpdateClusterMetadata", "UpdateInstanceMetadata", + "UpdateLogicalViewMetadata", + "UpdateLogicalViewRequest", + "UpdateMaterializedViewMetadata", + "UpdateMaterializedViewRequest", "CheckConsistencyRequest", "CheckConsistencyResponse", "CopyBackupMetadata", @@ -197,6 +231,8 @@ "Cluster", "HotTablet", "Instance", + "LogicalView", + "MaterializedView", "AuthorizedView", "Backup", "BackupInfo", diff --git a/google/cloud/bigtable_admin_v2/types/bigtable_instance_admin.py b/google/cloud/bigtable_admin_v2/types/bigtable_instance_admin.py index 4e5ddfd6e..5bed1c4f7 100644 --- a/google/cloud/bigtable_admin_v2/types/bigtable_instance_admin.py +++ b/google/cloud/bigtable_admin_v2/types/bigtable_instance_admin.py @@ -53,6 +53,22 @@ "UpdateAppProfileMetadata", "ListHotTabletsRequest", "ListHotTabletsResponse", + "CreateLogicalViewRequest", + "CreateLogicalViewMetadata", + "GetLogicalViewRequest", + "ListLogicalViewsRequest", + "ListLogicalViewsResponse", + "UpdateLogicalViewRequest", + "UpdateLogicalViewMetadata", + "DeleteLogicalViewRequest", + "CreateMaterializedViewRequest", + "CreateMaterializedViewMetadata", + "GetMaterializedViewRequest", + "ListMaterializedViewsRequest", + "ListMaterializedViewsResponse", + "UpdateMaterializedViewRequest", + "UpdateMaterializedViewMetadata", + "DeleteMaterializedViewRequest", }, ) @@ -77,8 +93,7 @@ class CreateInstanceRequest(proto.Message): mapped by desired cluster ID, e.g., just ``mycluster`` rather than ``projects/myproject/instances/myinstance/clusters/mycluster``. - Fields marked ``OutputOnly`` must be left blank. Currently, - at most four clusters can be specified. + Fields marked ``OutputOnly`` must be left blank. """ parent: str = proto.Field( @@ -888,4 +903,462 @@ def raw_page(self): ) +class CreateLogicalViewRequest(proto.Message): + r"""Request message for BigtableInstanceAdmin.CreateLogicalView. + + Attributes: + parent (str): + Required. The parent instance where this logical view will + be created. Format: + ``projects/{project}/instances/{instance}``. + logical_view_id (str): + Required. The ID to use for the logical view, + which will become the final component of the + logical view's resource name. + logical_view (google.cloud.bigtable_admin_v2.types.LogicalView): + Required. The logical view to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + logical_view_id: str = proto.Field( + proto.STRING, + number=2, + ) + logical_view: gba_instance.LogicalView = proto.Field( + proto.MESSAGE, + number=3, + message=gba_instance.LogicalView, + ) + + +class CreateLogicalViewMetadata(proto.Message): + r"""The metadata for the Operation returned by CreateLogicalView. + + Attributes: + original_request (google.cloud.bigtable_admin_v2.types.CreateLogicalViewRequest): + The request that prompted the initiation of + this CreateLogicalView operation. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which this operation started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + If set, the time at which this operation + finished or was canceled. + """ + + original_request: "CreateLogicalViewRequest" = proto.Field( + proto.MESSAGE, + number=1, + message="CreateLogicalViewRequest", + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class GetLogicalViewRequest(proto.Message): + r"""Request message for BigtableInstanceAdmin.GetLogicalView. + + Attributes: + name (str): + Required. The unique name of the requested logical view. + Values are of the form + ``projects/{project}/instances/{instance}/logicalViews/{logical_view}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListLogicalViewsRequest(proto.Message): + r"""Request message for BigtableInstanceAdmin.ListLogicalViews. + + Attributes: + parent (str): + Required. The unique name of the instance for which the list + of logical views is requested. Values are of the form + ``projects/{project}/instances/{instance}``. + page_size (int): + Optional. The maximum number of logical views + to return. The service may return fewer than + this value + page_token (str): + Optional. A page token, received from a previous + ``ListLogicalViews`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListLogicalViews`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListLogicalViewsResponse(proto.Message): + r"""Response message for BigtableInstanceAdmin.ListLogicalViews. + + Attributes: + logical_views (MutableSequence[google.cloud.bigtable_admin_v2.types.LogicalView]): + The list of requested logical views. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + logical_views: MutableSequence[gba_instance.LogicalView] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gba_instance.LogicalView, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateLogicalViewRequest(proto.Message): + r"""Request message for BigtableInstanceAdmin.UpdateLogicalView. + + Attributes: + logical_view (google.cloud.bigtable_admin_v2.types.LogicalView): + Required. The logical view to update. + + The logical view's ``name`` field is used to identify the + view to update. Format: + ``projects/{project}/instances/{instance}/logicalViews/{logical_view}``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + """ + + logical_view: gba_instance.LogicalView = proto.Field( + proto.MESSAGE, + number=1, + message=gba_instance.LogicalView, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateLogicalViewMetadata(proto.Message): + r"""The metadata for the Operation returned by UpdateLogicalView. + + Attributes: + original_request (google.cloud.bigtable_admin_v2.types.UpdateLogicalViewRequest): + The request that prompted the initiation of + this UpdateLogicalView operation. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which this operation was started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + If set, the time at which this operation + finished or was canceled. + """ + + original_request: "UpdateLogicalViewRequest" = proto.Field( + proto.MESSAGE, + number=1, + message="UpdateLogicalViewRequest", + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteLogicalViewRequest(proto.Message): + r"""Request message for BigtableInstanceAdmin.DeleteLogicalView. + + Attributes: + name (str): + Required. The unique name of the logical view to be deleted. + Format: + ``projects/{project}/instances/{instance}/logicalViews/{logical_view}``. + etag (str): + Optional. The current etag of the logical + view. If an etag is provided and does not match + the current etag of the logical view, deletion + will be blocked and an ABORTED error will be + returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateMaterializedViewRequest(proto.Message): + r"""Request message for + BigtableInstanceAdmin.CreateMaterializedView. + + Attributes: + parent (str): + Required. The parent instance where this materialized view + will be created. Format: + ``projects/{project}/instances/{instance}``. + materialized_view_id (str): + Required. The ID to use for the materialized + view, which will become the final component of + the materialized view's resource name. + materialized_view (google.cloud.bigtable_admin_v2.types.MaterializedView): + Required. The materialized view to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + materialized_view_id: str = proto.Field( + proto.STRING, + number=2, + ) + materialized_view: gba_instance.MaterializedView = proto.Field( + proto.MESSAGE, + number=3, + message=gba_instance.MaterializedView, + ) + + +class CreateMaterializedViewMetadata(proto.Message): + r"""The metadata for the Operation returned by + CreateMaterializedView. + + Attributes: + original_request (google.cloud.bigtable_admin_v2.types.CreateMaterializedViewRequest): + The request that prompted the initiation of + this CreateMaterializedView operation. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which this operation started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + If set, the time at which this operation + finished or was canceled. + """ + + original_request: "CreateMaterializedViewRequest" = proto.Field( + proto.MESSAGE, + number=1, + message="CreateMaterializedViewRequest", + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class GetMaterializedViewRequest(proto.Message): + r"""Request message for + BigtableInstanceAdmin.GetMaterializedView. + + Attributes: + name (str): + Required. The unique name of the requested materialized + view. Values are of the form + ``projects/{project}/instances/{instance}/materializedViews/{materialized_view}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMaterializedViewsRequest(proto.Message): + r"""Request message for + BigtableInstanceAdmin.ListMaterializedViews. + + Attributes: + parent (str): + Required. The unique name of the instance for which the list + of materialized views is requested. Values are of the form + ``projects/{project}/instances/{instance}``. + page_size (int): + Optional. The maximum number of materialized + views to return. The service may return fewer + than this value + page_token (str): + Optional. A page token, received from a previous + ``ListMaterializedViews`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListMaterializedViews`` must match the call that provided + the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMaterializedViewsResponse(proto.Message): + r"""Response message for + BigtableInstanceAdmin.ListMaterializedViews. + + Attributes: + materialized_views (MutableSequence[google.cloud.bigtable_admin_v2.types.MaterializedView]): + The list of requested materialized views. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + materialized_views: MutableSequence[ + gba_instance.MaterializedView + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gba_instance.MaterializedView, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateMaterializedViewRequest(proto.Message): + r"""Request message for + BigtableInstanceAdmin.UpdateMaterializedView. + + Attributes: + materialized_view (google.cloud.bigtable_admin_v2.types.MaterializedView): + Required. The materialized view to update. + + The materialized view's ``name`` field is used to identify + the view to update. Format: + ``projects/{project}/instances/{instance}/materializedViews/{materialized_view}``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + """ + + materialized_view: gba_instance.MaterializedView = proto.Field( + proto.MESSAGE, + number=1, + message=gba_instance.MaterializedView, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateMaterializedViewMetadata(proto.Message): + r"""The metadata for the Operation returned by + UpdateMaterializedView. + + Attributes: + original_request (google.cloud.bigtable_admin_v2.types.UpdateMaterializedViewRequest): + The request that prompted the initiation of + this UpdateMaterializedView operation. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which this operation was started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + If set, the time at which this operation + finished or was canceled. + """ + + original_request: "UpdateMaterializedViewRequest" = proto.Field( + proto.MESSAGE, + number=1, + message="UpdateMaterializedViewRequest", + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteMaterializedViewRequest(proto.Message): + r"""Request message for + BigtableInstanceAdmin.DeleteMaterializedView. + + Attributes: + name (str): + Required. The unique name of the materialized view to be + deleted. Format: + ``projects/{project}/instances/{instance}/materializedViews/{materialized_view}``. + etag (str): + Optional. The current etag of the + materialized view. If an etag is provided and + does not match the current etag of the + materialized view, deletion will be blocked and + an ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/bigtable_admin_v2/types/bigtable_table_admin.py b/google/cloud/bigtable_admin_v2/types/bigtable_table_admin.py index 9d1bf3ef5..ab8273a0a 100644 --- a/google/cloud/bigtable_admin_v2/types/bigtable_table_admin.py +++ b/google/cloud/bigtable_admin_v2/types/bigtable_table_admin.py @@ -480,9 +480,13 @@ class UpdateTableRequest(proto.Message): - ``change_stream_config`` - ``change_stream_config.retention_period`` - ``deletion_protection`` + - ``row_key_schema`` If ``column_families`` is set in ``update_mask``, it will return an UNIMPLEMENTED error. + ignore_warnings (bool): + Optional. If true, ignore safety checks when + updating the table. """ table: gba_table.Table = proto.Field( @@ -495,6 +499,10 @@ class UpdateTableRequest(proto.Message): number=2, message=field_mask_pb2.FieldMask, ) + ignore_warnings: bool = proto.Field( + proto.BOOL, + number=3, + ) class UpdateTableMetadata(proto.Message): diff --git a/google/cloud/bigtable_admin_v2/types/instance.py b/google/cloud/bigtable_admin_v2/types/instance.py index 34b52acd2..19a17c698 100644 --- a/google/cloud/bigtable_admin_v2/types/instance.py +++ b/google/cloud/bigtable_admin_v2/types/instance.py @@ -32,6 +32,8 @@ "Cluster", "AppProfile", "HotTablet", + "LogicalView", + "MaterializedView", }, ) @@ -55,7 +57,8 @@ class Instance(proto.Message): any time, but should be kept globally unique to avoid confusion. state (google.cloud.bigtable_admin_v2.types.Instance.State): - (``OutputOnly``) The current state of the instance. + Output only. The current state of the + instance. type_ (google.cloud.bigtable_admin_v2.types.Instance.Type): The type of the instance. Defaults to ``PRODUCTION``. labels (MutableMapping[str, str]): @@ -74,14 +77,18 @@ class Instance(proto.Message): resource. - Keys and values must both be under 128 bytes. create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. A server-assigned timestamp representing when - this Instance was created. For instances created before this + Output only. A commit timestamp representing when this + Instance was created. For instances created before this field was added (August 2021), this value is ``seconds: 0, nanos: 1``. satisfies_pzs (bool): Output only. Reserved for future use. This field is a member of `oneof`_ ``_satisfies_pzs``. + satisfies_pzi (bool): + Output only. Reserved for future use. + + This field is a member of `oneof`_ ``_satisfies_pzi``. """ class State(proto.Enum): @@ -157,6 +164,11 @@ class Type(proto.Enum): number=8, optional=True, ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=11, + optional=True, + ) class AutoscalingTargets(proto.Message): @@ -234,9 +246,10 @@ class Cluster(proto.Message): Output only. The current state of the cluster. serve_nodes (int): - The number of nodes allocated to this - cluster. More nodes enable higher throughput and - more consistent performance. + The number of nodes in the cluster. If no + value is set, Cloud Bigtable automatically + allocates nodes based on your data footprint and + optimized for 50% storage utilization. node_scaling_factor (google.cloud.bigtable_admin_v2.types.Cluster.NodeScalingFactor): Immutable. The node scaling factor of this cluster. @@ -361,9 +374,8 @@ class EncryptionConfig(proto.Message): ``cloudkms.cryptoKeyEncrypterDecrypter`` role on the CMEK key. 2) Only regional keys can be used and the region of the CMEK - key must match the region of the cluster. - 3) All clusters within an instance must use the same CMEK - key. Values are of the form + key must match the region of the cluster. Values are of + the form ``projects/{project}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}`` """ @@ -583,17 +595,10 @@ class StandardIsolation(proto.Message): class DataBoostIsolationReadOnly(proto.Message): r"""Data Boost is a serverless compute capability that lets you - run high-throughput read jobs on your Bigtable data, without - impacting the performance of the clusters that handle your - application traffic. Currently, Data Boost exclusively supports - read-only use-cases with single-cluster routing. - - Data Boost reads are only guaranteed to see the results of - writes that were written at least 30 minutes ago. This means - newly written values may not become visible for up to 30m, and - also means that old values may remain visible for up to 30m - after being deleted or overwritten. To mitigate the staleness of - the data, users may either wait 30m, or use CheckConsistency. + run high-throughput read jobs and queries on your Bigtable data, + without impacting the performance of the clusters that handle + your application traffic. Data Boost supports read-only use + cases with single-cluster routing. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -738,4 +743,77 @@ class HotTablet(proto.Message): ) +class LogicalView(proto.Message): + r"""A SQL logical view object that can be referenced in SQL + queries. + + Attributes: + name (str): + Identifier. The unique name of the logical view. Format: + ``projects/{project}/instances/{instance}/logicalViews/{logical_view}`` + query (str): + Required. The logical view's select query. + etag (str): + Optional. The etag for this logical view. + This may be sent on update requests to ensure + that the client has an up-to-date value before + proceeding. The server returns an ABORTED error + on a mismatched etag. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class MaterializedView(proto.Message): + r"""A materialized view object that can be referenced in SQL + queries. + + Attributes: + name (str): + Identifier. The unique name of the materialized view. + Format: + ``projects/{project}/instances/{instance}/materializedViews/{materialized_view}`` + query (str): + Required. Immutable. The materialized view's + select query. + etag (str): + Optional. The etag for this materialized + view. This may be sent on update requests to + ensure that the client has an up-to-date value + before proceeding. The server returns an ABORTED + error on a mismatched etag. + deletion_protection (bool): + Set to true to make the MaterializedView + protected against deletion. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + deletion_protection: bool = proto.Field( + proto.BOOL, + number=6, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/bigtable_admin_v2/types/table.py b/google/cloud/bigtable_admin_v2/types/table.py index 241d7853c..6dcf7b4a8 100644 --- a/google/cloud/bigtable_admin_v2/types/table.py +++ b/google/cloud/bigtable_admin_v2/types/table.py @@ -163,6 +163,59 @@ class Table(proto.Message): disabled. This field is a member of `oneof`_ ``automated_backup_config``. + row_key_schema (google.cloud.bigtable_admin_v2.types.Type.Struct): + The row key schema for this table. The schema is used to + decode the raw row key bytes into a structured format. The + order of field declarations in this schema is important, as + it reflects how the raw row key bytes are structured. + Currently, this only affects how the key is read via a + GoogleSQL query from the ExecuteQuery API. + + For a SQL query, the \_key column is still read as raw + bytes. But queries can reference the key fields by name, + which will be decoded from \_key using provided type and + encoding. Queries that reference key fields will fail if + they encounter an invalid row key. + + For example, if \_key = + "some_id#2024-04-30#\x00\x13\x00\xf3" with the following + schema: { fields { field_name: "id" type { string { + encoding: utf8_bytes {} } } } fields { field_name: "date" + type { string { encoding: utf8_bytes {} } } } fields { + field_name: "product_code" type { int64 { encoding: + big_endian_bytes {} } } } encoding { delimited_bytes { + delimiter: "#" } } } + + | The decoded key parts would be: id = "some_id", date = + "2024-04-30", product_code = 1245427 The query "SELECT + \_key, product_code FROM table" will return two columns: + /------------------------------------------------------ + | \| \_key \| product_code \| \| + --------------------------------------|--------------\| \| + "some_id#2024-04-30#\x00\x13\x00\xf3" \| 1245427 \| + ------------------------------------------------------/ + + The schema has the following invariants: (1) The decoded + field values are order-preserved. For read, the field values + will be decoded in sorted mode from the raw bytes. (2) Every + field in the schema must specify a non-empty name. (3) Every + field must specify a type with an associated encoding. The + type is limited to scalar types only: Array, Map, Aggregate, + and Struct are not allowed. (4) The field names must not + collide with existing column family names and reserved + keywords "_key" and "_timestamp". + + The following update operations are allowed for + row_key_schema: + + - Update from an empty schema to a new schema. + - Remove the existing schema. This operation requires + setting the ``ignore_warnings`` flag to ``true``, since + it might be a backward incompatible change. Without the + flag, the update request will fail with an + INVALID_ARGUMENT error. Any other row key schema update + operation (e.g. update existing schema columns names or + types) is currently unsupported. """ class TimestampGranularity(proto.Enum): @@ -343,6 +396,11 @@ class AutomatedBackupPolicy(proto.Message): oneof="automated_backup_config", message=AutomatedBackupPolicy, ) + row_key_schema: types.Type.Struct = proto.Field( + proto.MESSAGE, + number=15, + message=types.Type.Struct, + ) class AuthorizedView(proto.Message): diff --git a/google/cloud/bigtable_admin_v2/types/types.py b/google/cloud/bigtable_admin_v2/types/types.py index 7d1d99034..ec5744156 100644 --- a/google/cloud/bigtable_admin_v2/types/types.py +++ b/google/cloud/bigtable_admin_v2/types/types.py @@ -35,34 +35,27 @@ class Type(proto.Message): features. For compatibility with Bigtable's existing untyped APIs, each - ``Type`` includes an ``Encoding`` which describes how to convert - to/from the underlying data. - - Each encoding also defines the following properties: - - - Order-preserving: Does the encoded value sort consistently with - the original typed value? Note that Bigtable will always sort - data based on the raw encoded value, *not* the decoded type. - - - Example: BYTES values sort in the same order as their raw - encodings. - - Counterexample: Encoding INT64 as a fixed-width decimal string - does *not* preserve sort order when dealing with negative - numbers. ``INT64(1) > INT64(-1)``, but - ``STRING("-00001") > STRING("00001)``. - - - Self-delimiting: If we concatenate two encoded values, can we - always tell where the first one ends and the second one begins? - - - Example: If we encode INT64s to fixed-width STRINGs, the first - value will always contain exactly N digits, possibly preceded - by a sign. - - Counterexample: If we concatenate two UTF-8 encoded STRINGs, - we have no way to tell where the first one ends. - - - Compatibility: Which other systems have matching encoding - schemes? For example, does this encoding have a GoogleSQL - equivalent? HBase? Java? + ``Type`` includes an ``Encoding`` which describes how to convert to + or from the underlying data. + + Each encoding can operate in one of two modes: + + - Sorted: In this mode, Bigtable guarantees that + ``Encode(X) <= Encode(Y)`` if and only if ``X <= Y``. This is + useful anywhere sort order is important, for example when + encoding keys. + - Distinct: In this mode, Bigtable guarantees that if ``X != Y`` + then ``Encode(X) != Encode(Y)``. However, the converse is not + guaranteed. For example, both "{'foo': '1', 'bar': '2'}" and + "{'bar': '2', 'foo': '1'}" are valid encodings of the same JSON + value. + + The API clearly documents which mode is used wherever an encoding + can be configured. Each encoding also documents which values are + supported in which modes. For example, when encoding INT64 as a + numeric STRING, negative numbers cannot be encoded in sorted mode. + This is because ``INT64(1) > INT64(-1)``, but + ``STRING("-00001") > STRING("00001")``. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -127,12 +120,12 @@ class Bytes(proto.Message): Attributes: encoding (google.cloud.bigtable_admin_v2.types.Type.Bytes.Encoding): - The encoding to use when converting to/from - lower level types. + The encoding to use when converting to or + from lower level types. """ class Encoding(proto.Message): - r"""Rules used to convert to/from lower level types. + r"""Rules used to convert to or from lower level types. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -144,11 +137,11 @@ class Encoding(proto.Message): """ class Raw(proto.Message): - r"""Leaves the value "as-is" + r"""Leaves the value as-is. + + Sorted mode: all values are supported. - - Order-preserving? Yes - - Self-delimiting? No - - Compatibility? N/A + Distinct mode: all values are supported. """ @@ -171,12 +164,12 @@ class String(proto.Message): Attributes: encoding (google.cloud.bigtable_admin_v2.types.Type.String.Encoding): - The encoding to use when converting to/from - lower level types. + The encoding to use when converting to or + from lower level types. """ class Encoding(proto.Message): - r"""Rules used to convert to/from lower level types. + r"""Rules used to convert to or from lower level types. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -200,15 +193,20 @@ class Utf8Raw(proto.Message): r"""Deprecated: prefer the equivalent ``Utf8Bytes``.""" class Utf8Bytes(proto.Message): - r"""UTF-8 encoding + r"""UTF-8 encoding. - - Order-preserving? Yes (code point order) - - Self-delimiting? No - - Compatibility? + Sorted mode: - - BigQuery Federation ``TEXT`` encoding - - HBase ``Bytes.toBytes`` - - Java ``String#getBytes(StandardCharsets.UTF_8)`` + - All values are supported. + - Code point order is preserved. + + Distinct mode: all values are supported. + + Compatible with: + + - BigQuery ``TEXT`` encoding + - HBase ``Bytes.toBytes`` + - Java ``String#getBytes(StandardCharsets.UTF_8)`` """ @@ -236,12 +234,17 @@ class Int64(proto.Message): Attributes: encoding (google.cloud.bigtable_admin_v2.types.Type.Int64.Encoding): - The encoding to use when converting to/from - lower level types. + The encoding to use when converting to or + from lower level types. """ class Encoding(proto.Message): - r"""Rules used to convert to/from lower level types. + r"""Rules used to convert to or from lower level types. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -249,20 +252,25 @@ class Encoding(proto.Message): big_endian_bytes (google.cloud.bigtable_admin_v2.types.Type.Int64.Encoding.BigEndianBytes): Use ``BigEndianBytes`` encoding. + This field is a member of `oneof`_ ``encoding``. + ordered_code_bytes (google.cloud.bigtable_admin_v2.types.Type.Int64.Encoding.OrderedCodeBytes): + Use ``OrderedCodeBytes`` encoding. + This field is a member of `oneof`_ ``encoding``. """ class BigEndianBytes(proto.Message): - r"""Encodes the value as an 8-byte big endian twos complement ``Bytes`` - value. + r"""Encodes the value as an 8-byte big-endian two's complement value. + + Sorted mode: non-negative values are supported. - - Order-preserving? No (positive values only) - - Self-delimiting? Yes - - Compatibility? + Distinct mode: all values are supported. - - BigQuery Federation ``BINARY`` encoding - - HBase ``Bytes.toBytes`` - - Java ``ByteBuffer.putLong()`` with ``ByteOrder.BIG_ENDIAN`` + Compatible with: + + - BigQuery ``BINARY`` encoding + - HBase ``Bytes.toBytes`` + - Java ``ByteBuffer.putLong()`` with ``ByteOrder.BIG_ENDIAN`` Attributes: bytes_type (google.cloud.bigtable_admin_v2.types.Type.Bytes): @@ -275,12 +283,28 @@ class BigEndianBytes(proto.Message): message="Type.Bytes", ) + class OrderedCodeBytes(proto.Message): + r"""Encodes the value in a variable length binary format of up to + 10 bytes. Values that are closer to zero use fewer bytes. + + Sorted mode: all values are supported. + + Distinct mode: all values are supported. + + """ + big_endian_bytes: "Type.Int64.Encoding.BigEndianBytes" = proto.Field( proto.MESSAGE, number=1, oneof="encoding", message="Type.Int64.Encoding.BigEndianBytes", ) + ordered_code_bytes: "Type.Int64.Encoding.OrderedCodeBytes" = proto.Field( + proto.MESSAGE, + number=2, + oneof="encoding", + message="Type.Int64.Encoding.OrderedCodeBytes", + ) encoding: "Type.Int64.Encoding" = proto.Field( proto.MESSAGE, @@ -307,8 +331,43 @@ class Timestamp(proto.Message): r"""Timestamp Values of type ``Timestamp`` are stored in ``Value.timestamp_value``. + Attributes: + encoding (google.cloud.bigtable_admin_v2.types.Type.Timestamp.Encoding): + The encoding to use when converting to or + from lower level types. """ + class Encoding(proto.Message): + r"""Rules used to convert to or from lower level types. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + unix_micros_int64 (google.cloud.bigtable_admin_v2.types.Type.Int64.Encoding): + Encodes the number of microseconds since the Unix epoch + using the given ``Int64`` encoding. Values must be + microsecond-aligned. + + Compatible with: + + - Java ``Instant.truncatedTo()`` with ``ChronoUnit.MICROS`` + + This field is a member of `oneof`_ ``encoding``. + """ + + unix_micros_int64: "Type.Int64.Encoding" = proto.Field( + proto.MESSAGE, + number=1, + oneof="encoding", + message="Type.Int64.Encoding", + ) + + encoding: "Type.Timestamp.Encoding" = proto.Field( + proto.MESSAGE, + number=1, + message="Type.Timestamp.Encoding", + ) + class Date(proto.Message): r"""Date Values of type ``Date`` are stored in ``Value.date_value``.""" @@ -322,6 +381,9 @@ class Struct(proto.Message): fields (MutableSequence[google.cloud.bigtable_admin_v2.types.Type.Struct.Field]): The names and types of the fields in this struct. + encoding (google.cloud.bigtable_admin_v2.types.Type.Struct.Encoding): + The encoding to use when converting to or + from lower level types. """ class Field(proto.Message): @@ -345,11 +407,146 @@ class Field(proto.Message): message="Type", ) + class Encoding(proto.Message): + r"""Rules used to convert to or from lower level types. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + singleton (google.cloud.bigtable_admin_v2.types.Type.Struct.Encoding.Singleton): + Use ``Singleton`` encoding. + + This field is a member of `oneof`_ ``encoding``. + delimited_bytes (google.cloud.bigtable_admin_v2.types.Type.Struct.Encoding.DelimitedBytes): + Use ``DelimitedBytes`` encoding. + + This field is a member of `oneof`_ ``encoding``. + ordered_code_bytes (google.cloud.bigtable_admin_v2.types.Type.Struct.Encoding.OrderedCodeBytes): + User ``OrderedCodeBytes`` encoding. + + This field is a member of `oneof`_ ``encoding``. + """ + + class Singleton(proto.Message): + r"""Uses the encoding of ``fields[0].type`` as-is. Only valid if + ``fields.size == 1``. + + """ + + class DelimitedBytes(proto.Message): + r"""Fields are encoded independently and concatenated with a + configurable ``delimiter`` in between. + + A struct with no fields defined is encoded as a single + ``delimiter``. + + Sorted mode: + + - Fields are encoded in sorted mode. + - Encoded field values must not contain any bytes <= + ``delimiter[0]`` + - Element-wise order is preserved: ``A < B`` if ``A[0] < B[0]``, or + if ``A[0] == B[0] && A[1] < B[1]``, etc. Strict prefixes sort + first. + + Distinct mode: + + - Fields are encoded in distinct mode. + - Encoded field values must not contain ``delimiter[0]``. + + Attributes: + delimiter (bytes): + Byte sequence used to delimit concatenated + fields. The delimiter must contain at least 1 + character and at most 50 characters. + """ + + delimiter: bytes = proto.Field( + proto.BYTES, + number=1, + ) + + class OrderedCodeBytes(proto.Message): + r"""Fields are encoded independently and concatenated with the fixed + byte pair {0x00, 0x01} in between. + + Any null (0x00) byte in an encoded field is replaced by the fixed + byte pair {0x00, 0xFF}. + + Fields that encode to the empty string "" have special handling: + + - If *every* field encodes to "", or if the STRUCT has no fields + defined, then the STRUCT is encoded as the fixed byte pair {0x00, + 0x00}. + - Otherwise, the STRUCT only encodes until the last non-empty + field, omitting any trailing empty fields. Any empty fields that + aren't omitted are replaced with the fixed byte pair {0x00, + 0x00}. + + Examples: + + - STRUCT() -> "\00\00" + - STRUCT("") -> "\00\00" + - STRUCT("", "") -> "\00\00" + - STRUCT("", "B") -> "\00\00" + "\00\01" + "B" + - STRUCT("A", "") -> "A" + - STRUCT("", "B", "") -> "\00\00" + "\00\01" + "B" + - STRUCT("A", "", "C") -> "A" + "\00\01" + "\00\00" + "\00\01" + + "C" + + Since null bytes are always escaped, this encoding can cause size + blowup for encodings like ``Int64.BigEndianBytes`` that are likely + to produce many such bytes. + + Sorted mode: + + - Fields are encoded in sorted mode. + - All values supported by the field encodings are allowed + - Element-wise order is preserved: ``A < B`` if ``A[0] < B[0]``, or + if ``A[0] == B[0] && A[1] < B[1]``, etc. Strict prefixes sort + first. + + Distinct mode: + + - Fields are encoded in distinct mode. + - All values supported by the field encodings are allowed. + + """ + + singleton: "Type.Struct.Encoding.Singleton" = proto.Field( + proto.MESSAGE, + number=1, + oneof="encoding", + message="Type.Struct.Encoding.Singleton", + ) + delimited_bytes: "Type.Struct.Encoding.DelimitedBytes" = proto.Field( + proto.MESSAGE, + number=2, + oneof="encoding", + message="Type.Struct.Encoding.DelimitedBytes", + ) + ordered_code_bytes: "Type.Struct.Encoding.OrderedCodeBytes" = proto.Field( + proto.MESSAGE, + number=3, + oneof="encoding", + message="Type.Struct.Encoding.OrderedCodeBytes", + ) + fields: MutableSequence["Type.Struct.Field"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Type.Struct.Field", ) + encoding: "Type.Struct.Encoding" = proto.Field( + proto.MESSAGE, + number=2, + message="Type.Struct.Encoding", + ) class Array(proto.Message): r"""An ordered list of elements of a given type. Values of type diff --git a/google/cloud/bigtable_v2/__init__.py b/google/cloud/bigtable_v2/__init__.py index f2b3ddf28..a7ff5ac1d 100644 --- a/google/cloud/bigtable_v2/__init__.py +++ b/google/cloud/bigtable_v2/__init__.py @@ -33,6 +33,8 @@ from .types.bigtable import MutateRowsResponse from .types.bigtable import PingAndWarmRequest from .types.bigtable import PingAndWarmResponse +from .types.bigtable import PrepareQueryRequest +from .types.bigtable import PrepareQueryResponse from .types.bigtable import RateLimitInfo from .types.bigtable import ReadChangeStreamRequest from .types.bigtable import ReadChangeStreamResponse @@ -99,6 +101,8 @@ "PartialResultSet", "PingAndWarmRequest", "PingAndWarmResponse", + "PrepareQueryRequest", + "PrepareQueryResponse", "ProtoFormat", "ProtoRows", "ProtoRowsBatch", diff --git a/google/cloud/bigtable_v2/gapic_metadata.json b/google/cloud/bigtable_v2/gapic_metadata.json index fd47c0435..83504fbc1 100644 --- a/google/cloud/bigtable_v2/gapic_metadata.json +++ b/google/cloud/bigtable_v2/gapic_metadata.json @@ -40,6 +40,11 @@ "ping_and_warm" ] }, + "PrepareQuery": { + "methods": [ + "prepare_query" + ] + }, "ReadChangeStream": { "methods": [ "read_change_stream" @@ -95,6 +100,11 @@ "ping_and_warm" ] }, + "PrepareQuery": { + "methods": [ + "prepare_query" + ] + }, "ReadChangeStream": { "methods": [ "read_change_stream" @@ -150,6 +160,11 @@ "ping_and_warm" ] }, + "PrepareQuery": { + "methods": [ + "prepare_query" + ] + }, "ReadChangeStream": { "methods": [ "read_change_stream" diff --git a/google/cloud/bigtable_v2/services/bigtable/async_client.py b/google/cloud/bigtable_v2/services/bigtable/async_client.py index 08317e1eb..3d4e2373d 100644 --- a/google/cloud/bigtable_v2/services/bigtable/async_client.py +++ b/google/cloud/bigtable_v2/services/bigtable/async_client.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import logging as std_logging from collections import OrderedDict import re from typing import ( @@ -48,10 +49,20 @@ from google.cloud.bigtable_v2.types import bigtable from google.cloud.bigtable_v2.types import data from google.cloud.bigtable_v2.types import request_stats +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import BigtableTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import BigtableGrpcAsyncIOTransport from .client import BigtableClient +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + class BigtableAsyncClient: """Service for reading from and writing to existing Bigtable @@ -71,6 +82,10 @@ class BigtableAsyncClient: parse_authorized_view_path = staticmethod(BigtableClient.parse_authorized_view_path) instance_path = staticmethod(BigtableClient.instance_path) parse_instance_path = staticmethod(BigtableClient.parse_instance_path) + materialized_view_path = staticmethod(BigtableClient.materialized_view_path) + parse_materialized_view_path = staticmethod( + BigtableClient.parse_materialized_view_path + ) table_path = staticmethod(BigtableClient.table_path) parse_table_path = staticmethod(BigtableClient.parse_table_path) common_billing_account_path = staticmethod( @@ -255,6 +270,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.bigtable_v2.BigtableAsyncClient`.", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.bigtable.v2.Bigtable", + "credentialsType": None, + }, + ) + def read_rows( self, request: Optional[Union[bigtable.ReadRowsRequest, dict]] = None, @@ -263,7 +300,7 @@ def read_rows( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Awaitable[AsyncIterable[bigtable.ReadRowsResponse]]: r"""Streams back the contents of all requested rows in key order, optionally applying the same Reader filter to @@ -298,8 +335,10 @@ def read_rows( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: AsyncIterable[google.cloud.bigtable_v2.types.ReadRowsResponse]: @@ -310,7 +349,10 @@ def read_rows( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, app_profile_id]) + flattened_params = [table_name, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -357,9 +399,9 @@ def read_rows( ) if header_params: - metadata = tuple(metadata) - if all(m[0] != gapic_v1.routing_header.ROUTING_METADATA_KEY for m in metadata): - metadata += (gapic_v1.routing_header.to_grpc_metadata(header_params),) + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -383,7 +425,7 @@ def sample_row_keys( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Awaitable[AsyncIterable[bigtable.SampleRowKeysResponse]]: r"""Returns a sample of row keys in the table. The returned row keys will delimit contiguous sections of @@ -417,8 +459,10 @@ def sample_row_keys( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: AsyncIterable[google.cloud.bigtable_v2.types.SampleRowKeysResponse]: @@ -429,7 +473,10 @@ def sample_row_keys( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, app_profile_id]) + flattened_params = [table_name, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -476,9 +523,9 @@ def sample_row_keys( ) if header_params: - metadata = tuple(metadata) - if all(m[0] != gapic_v1.routing_header.ROUTING_METADATA_KEY for m in metadata): - metadata += (gapic_v1.routing_header.to_grpc_metadata(header_params),) + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -504,7 +551,7 @@ async def mutate_row( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.MutateRowResponse: r"""Mutates a row atomically. Cells already present in the row are left unchanged unless explicitly changed by ``mutation``. @@ -553,8 +600,10 @@ async def mutate_row( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_v2.types.MutateRowResponse: @@ -565,7 +614,10 @@ async def mutate_row( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, row_key, mutations, app_profile_id]) + flattened_params = [table_name, row_key, mutations, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -616,9 +668,9 @@ async def mutate_row( ) if header_params: - metadata = tuple(metadata) - if all(m[0] != gapic_v1.routing_header.ROUTING_METADATA_KEY for m in metadata): - metadata += (gapic_v1.routing_header.to_grpc_metadata(header_params),) + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -643,7 +695,7 @@ def mutate_rows( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Awaitable[AsyncIterable[bigtable.MutateRowsResponse]]: r"""Mutates multiple rows in a batch. Each individual row is mutated atomically as in MutateRow, but the entire @@ -689,8 +741,10 @@ def mutate_rows( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: AsyncIterable[google.cloud.bigtable_v2.types.MutateRowsResponse]: @@ -701,7 +755,10 @@ def mutate_rows( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, entries, app_profile_id]) + flattened_params = [table_name, entries, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -750,9 +807,9 @@ def mutate_rows( ) if header_params: - metadata = tuple(metadata) - if all(m[0] != gapic_v1.routing_header.ROUTING_METADATA_KEY for m in metadata): - metadata += (gapic_v1.routing_header.to_grpc_metadata(header_params),) + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -780,7 +837,7 @@ async def check_and_mutate_row( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.CheckAndMutateRowResponse: r"""Mutates a row atomically based on the output of a predicate Reader filter. @@ -851,8 +908,10 @@ async def check_and_mutate_row( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_v2.types.CheckAndMutateRowResponse: @@ -863,15 +922,16 @@ async def check_and_mutate_row( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any( - [ - table_name, - row_key, - predicate_filter, - true_mutations, - false_mutations, - app_profile_id, - ] + flattened_params = [ + table_name, + row_key, + predicate_filter, + true_mutations, + false_mutations, + app_profile_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 ) if request is not None and has_flattened_params: raise ValueError( @@ -927,9 +987,9 @@ async def check_and_mutate_row( ) if header_params: - metadata = tuple(metadata) - if all(m[0] != gapic_v1.routing_header.ROUTING_METADATA_KEY for m in metadata): - metadata += (gapic_v1.routing_header.to_grpc_metadata(header_params),) + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -953,7 +1013,7 @@ async def ping_and_warm( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.PingAndWarmResponse: r"""Warm up associated instance metadata for this connection. This call is not required but may be useful @@ -983,8 +1043,10 @@ async def ping_and_warm( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_v2.types.PingAndWarmResponse: @@ -996,7 +1058,10 @@ async def ping_and_warm( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, app_profile_id]) + flattened_params = [name, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1032,9 +1097,9 @@ async def ping_and_warm( header_params["app_profile_id"] = request.app_profile_id if header_params: - metadata = tuple(metadata) - if all(m[0] != gapic_v1.routing_header.ROUTING_METADATA_KEY for m in metadata): - metadata += (gapic_v1.routing_header.to_grpc_metadata(header_params),) + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -1060,7 +1125,7 @@ async def read_modify_write_row( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.ReadModifyWriteRowResponse: r"""Modifies a row atomically on the server. The method reads the latest existing timestamp and value from the @@ -1115,8 +1180,10 @@ async def read_modify_write_row( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_v2.types.ReadModifyWriteRowResponse: @@ -1127,7 +1194,10 @@ async def read_modify_write_row( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, row_key, rules, app_profile_id]) + flattened_params = [table_name, row_key, rules, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1178,9 +1248,9 @@ async def read_modify_write_row( ) if header_params: - metadata = tuple(metadata) - if all(m[0] != gapic_v1.routing_header.ROUTING_METADATA_KEY for m in metadata): - metadata += (gapic_v1.routing_header.to_grpc_metadata(header_params),) + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -1206,7 +1276,7 @@ def generate_initial_change_stream_partitions( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Awaitable[ AsyncIterable[bigtable.GenerateInitialChangeStreamPartitionsResponse] ]: @@ -1243,8 +1313,10 @@ def generate_initial_change_stream_partitions( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: AsyncIterable[google.cloud.bigtable_v2.types.GenerateInitialChangeStreamPartitionsResponse]: @@ -1257,7 +1329,10 @@ def generate_initial_change_stream_partitions( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, app_profile_id]) + flattened_params = [table_name, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1314,7 +1389,7 @@ def read_change_stream( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Awaitable[AsyncIterable[bigtable.ReadChangeStreamResponse]]: r"""NOTE: This API is intended to be used by Apache Beam BigtableIO. Reads changes from a table's change stream. @@ -1348,8 +1423,10 @@ def read_change_stream( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: AsyncIterable[google.cloud.bigtable_v2.types.ReadChangeStreamResponse]: @@ -1361,7 +1438,10 @@ def read_change_stream( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, app_profile_id]) + flattened_params = [table_name, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1408,6 +1488,124 @@ def read_change_stream( # Done; return the response. return response + async def prepare_query( + self, + request: Optional[Union[bigtable.PrepareQueryRequest, dict]] = None, + *, + instance_name: Optional[str] = None, + query: Optional[str] = None, + app_profile_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> bigtable.PrepareQueryResponse: + r"""Prepares a GoogleSQL query for execution on a + particular Bigtable instance. + + Args: + request (Optional[Union[google.cloud.bigtable_v2.types.PrepareQueryRequest, dict]]): + The request object. Request message for + Bigtable.PrepareQuery + instance_name (:class:`str`): + Required. The unique name of the instance against which + the query should be executed. Values are of the form + ``projects//instances/`` + + This corresponds to the ``instance_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Required. The query string. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app_profile_id (:class:`str`): + Optional. This value specifies routing for preparing the + query. Note that this ``app_profile_id`` is only used + for preparing the query. The actual query execution will + use the app profile specified in the + ``ExecuteQueryRequest``. If not specified, the + ``default`` application profile will be used. + + This corresponds to the ``app_profile_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_v2.types.PrepareQueryResponse: + Response message for + Bigtable.PrepareQueryResponse + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [instance_name, query, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable.PrepareQueryRequest): + request = bigtable.PrepareQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance_name is not None: + request.instance_name = instance_name + if query is not None: + request.query = query + if app_profile_id is not None: + request.app_profile_id = app_profile_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.prepare_query + ] + + header_params = {} + + routing_param_regex = re.compile("^(?Pprojects/[^/]+/instances/[^/]+)$") + regex_match = routing_param_regex.match(request.instance_name) + if regex_match and regex_match.group("name"): + header_params["name"] = regex_match.group("name") + + if request.app_profile_id: + header_params["app_profile_id"] = request.app_profile_id + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def execute_query( self, request: Optional[Union[bigtable.ExecuteQueryRequest, dict]] = None, @@ -1417,10 +1615,10 @@ def execute_query( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Awaitable[AsyncIterable[bigtable.ExecuteQueryResponse]]: - r"""Executes a BTQL query against a particular Cloud - Bigtable instance. + r"""Executes a SQL query against a particular Bigtable + instance. Args: request (Optional[Union[google.cloud.bigtable_v2.types.ExecuteQueryRequest, dict]]): @@ -1436,6 +1634,11 @@ def execute_query( should not be set. query (:class:`str`): Required. The query string. + + Exactly one of ``query`` and ``prepared_query`` is + required. Setting both or neither is an + ``INVALID_ARGUMENT``. + This corresponds to the ``query`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1450,8 +1653,10 @@ def execute_query( retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: AsyncIterable[google.cloud.bigtable_v2.types.ExecuteQueryResponse]: @@ -1462,7 +1667,10 @@ def execute_query( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([instance_name, query, app_profile_id]) + flattened_params = [instance_name, query, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1496,14 +1704,13 @@ def execute_query( if regex_match and regex_match.group("name"): header_params["name"] = regex_match.group("name") - if request.app_profile_id is not None: - # execute_query currently requires empty header support. TODO: remove after support is added + if request.app_profile_id: header_params["app_profile_id"] = request.app_profile_id if header_params: - metadata = tuple(metadata) - if all(m[0] != gapic_v1.routing_header.ROUTING_METADATA_KEY for m in metadata): - metadata += (gapic_v1.routing_header.to_grpc_metadata(header_params),) + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() diff --git a/google/cloud/bigtable_v2/services/bigtable/client.py b/google/cloud/bigtable_v2/services/bigtable/client.py index 42723c661..330a22520 100644 --- a/google/cloud/bigtable_v2/services/bigtable/client.py +++ b/google/cloud/bigtable_v2/services/bigtable/client.py @@ -14,6 +14,9 @@ # limitations under the License. # from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging import os import re from typing import ( @@ -49,9 +52,19 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + from google.cloud.bigtable_v2.types import bigtable from google.cloud.bigtable_v2.types import data from google.cloud.bigtable_v2.types import request_stats +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import BigtableTransport, DEFAULT_CLIENT_INFO from .transports.grpc import BigtableGrpcTransport from .transports.grpc_asyncio import BigtableGrpcAsyncIOTransport @@ -225,6 +238,28 @@ def parse_instance_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/instances/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def materialized_view_path( + project: str, + instance: str, + materialized_view: str, + ) -> str: + """Returns a fully-qualified materialized_view string.""" + return "projects/{project}/instances/{instance}/materializedViews/{materialized_view}".format( + project=project, + instance=instance, + materialized_view=materialized_view, + ) + + @staticmethod + def parse_materialized_view_path(path: str) -> Dict[str, str]: + """Parses a materialized_view path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/instances/(?P.+?)/materializedViews/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def table_path( project: str, @@ -516,6 +551,33 @@ def _validate_universe_domain(self): # NOTE (b/349488459): universe validation is disabled until further notice. return True + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + @property def api_endpoint(self): """Return the API endpoint used by the client instance. @@ -620,6 +682,10 @@ def __init__( # Initialize the universe domain validation. self._is_universe_domain_valid = False + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: raise ValueError( @@ -682,6 +748,29 @@ def __init__( api_audience=self._client_options.api_audience, ) + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.bigtable_v2.BigtableClient`.", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.bigtable.v2.Bigtable", + "credentialsType": None, + }, + ) + def read_rows( self, request: Optional[Union[bigtable.ReadRowsRequest, dict]] = None, @@ -690,7 +779,7 @@ def read_rows( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Iterable[bigtable.ReadRowsResponse]: r"""Streams back the contents of all requested rows in key order, optionally applying the same Reader filter to @@ -725,8 +814,10 @@ def read_rows( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: Iterable[google.cloud.bigtable_v2.types.ReadRowsResponse]: @@ -737,7 +828,10 @@ def read_rows( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, app_profile_id]) + flattened_params = [table_name, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -807,7 +901,7 @@ def sample_row_keys( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Iterable[bigtable.SampleRowKeysResponse]: r"""Returns a sample of row keys in the table. The returned row keys will delimit contiguous sections of @@ -841,8 +935,10 @@ def sample_row_keys( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: Iterable[google.cloud.bigtable_v2.types.SampleRowKeysResponse]: @@ -853,7 +949,10 @@ def sample_row_keys( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, app_profile_id]) + flattened_params = [table_name, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -925,7 +1024,7 @@ def mutate_row( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.MutateRowResponse: r"""Mutates a row atomically. Cells already present in the row are left unchanged unless explicitly changed by ``mutation``. @@ -974,8 +1073,10 @@ def mutate_row( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_v2.types.MutateRowResponse: @@ -986,7 +1087,10 @@ def mutate_row( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, row_key, mutations, app_profile_id]) + flattened_params = [table_name, row_key, mutations, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1061,7 +1165,7 @@ def mutate_rows( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Iterable[bigtable.MutateRowsResponse]: r"""Mutates multiple rows in a batch. Each individual row is mutated atomically as in MutateRow, but the entire @@ -1107,8 +1211,10 @@ def mutate_rows( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: Iterable[google.cloud.bigtable_v2.types.MutateRowsResponse]: @@ -1119,7 +1225,10 @@ def mutate_rows( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, entries, app_profile_id]) + flattened_params = [table_name, entries, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1195,7 +1304,7 @@ def check_and_mutate_row( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.CheckAndMutateRowResponse: r"""Mutates a row atomically based on the output of a predicate Reader filter. @@ -1266,8 +1375,10 @@ def check_and_mutate_row( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_v2.types.CheckAndMutateRowResponse: @@ -1278,15 +1389,16 @@ def check_and_mutate_row( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any( - [ - table_name, - row_key, - predicate_filter, - true_mutations, - false_mutations, - app_profile_id, - ] + flattened_params = [ + table_name, + row_key, + predicate_filter, + true_mutations, + false_mutations, + app_profile_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 ) if request is not None and has_flattened_params: raise ValueError( @@ -1365,7 +1477,7 @@ def ping_and_warm( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.PingAndWarmResponse: r"""Warm up associated instance metadata for this connection. This call is not required but may be useful @@ -1395,8 +1507,10 @@ def ping_and_warm( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_v2.types.PingAndWarmResponse: @@ -1408,7 +1522,10 @@ def ping_and_warm( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, app_profile_id]) + flattened_params = [name, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1469,7 +1586,7 @@ def read_modify_write_row( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.ReadModifyWriteRowResponse: r"""Modifies a row atomically on the server. The method reads the latest existing timestamp and value from the @@ -1524,8 +1641,10 @@ def read_modify_write_row( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.bigtable_v2.types.ReadModifyWriteRowResponse: @@ -1536,7 +1655,10 @@ def read_modify_write_row( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, row_key, rules, app_profile_id]) + flattened_params = [table_name, row_key, rules, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1612,7 +1734,7 @@ def generate_initial_change_stream_partitions( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Iterable[bigtable.GenerateInitialChangeStreamPartitionsResponse]: r"""NOTE: This API is intended to be used by Apache Beam BigtableIO. Returns the current list of partitions that make up the table's @@ -1647,8 +1769,10 @@ def generate_initial_change_stream_partitions( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: Iterable[google.cloud.bigtable_v2.types.GenerateInitialChangeStreamPartitionsResponse]: @@ -1661,7 +1785,10 @@ def generate_initial_change_stream_partitions( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, app_profile_id]) + flattened_params = [table_name, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1717,7 +1844,7 @@ def read_change_stream( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Iterable[bigtable.ReadChangeStreamResponse]: r"""NOTE: This API is intended to be used by Apache Beam BigtableIO. Reads changes from a table's change stream. @@ -1751,8 +1878,10 @@ def read_change_stream( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: Iterable[google.cloud.bigtable_v2.types.ReadChangeStreamResponse]: @@ -1764,7 +1893,10 @@ def read_change_stream( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([table_name, app_profile_id]) + flattened_params = [table_name, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1808,6 +1940,121 @@ def read_change_stream( # Done; return the response. return response + def prepare_query( + self, + request: Optional[Union[bigtable.PrepareQueryRequest, dict]] = None, + *, + instance_name: Optional[str] = None, + query: Optional[str] = None, + app_profile_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> bigtable.PrepareQueryResponse: + r"""Prepares a GoogleSQL query for execution on a + particular Bigtable instance. + + Args: + request (Union[google.cloud.bigtable_v2.types.PrepareQueryRequest, dict]): + The request object. Request message for + Bigtable.PrepareQuery + instance_name (str): + Required. The unique name of the instance against which + the query should be executed. Values are of the form + ``projects//instances/`` + + This corresponds to the ``instance_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (str): + Required. The query string. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app_profile_id (str): + Optional. This value specifies routing for preparing the + query. Note that this ``app_profile_id`` is only used + for preparing the query. The actual query execution will + use the app profile specified in the + ``ExecuteQueryRequest``. If not specified, the + ``default`` application profile will be used. + + This corresponds to the ``app_profile_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_v2.types.PrepareQueryResponse: + Response message for + Bigtable.PrepareQueryResponse + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [instance_name, query, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable.PrepareQueryRequest): + request = bigtable.PrepareQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance_name is not None: + request.instance_name = instance_name + if query is not None: + request.query = query + if app_profile_id is not None: + request.app_profile_id = app_profile_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.prepare_query] + + header_params = {} + + routing_param_regex = re.compile("^(?Pprojects/[^/]+/instances/[^/]+)$") + regex_match = routing_param_regex.match(request.instance_name) + if regex_match and regex_match.group("name"): + header_params["name"] = regex_match.group("name") + + if request.app_profile_id: + header_params["app_profile_id"] = request.app_profile_id + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def execute_query( self, request: Optional[Union[bigtable.ExecuteQueryRequest, dict]] = None, @@ -1817,10 +2064,10 @@ def execute_query( app_profile_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Iterable[bigtable.ExecuteQueryResponse]: - r"""Executes a BTQL query against a particular Cloud - Bigtable instance. + r"""Executes a SQL query against a particular Bigtable + instance. Args: request (Union[google.cloud.bigtable_v2.types.ExecuteQueryRequest, dict]): @@ -1836,6 +2083,11 @@ def execute_query( should not be set. query (str): Required. The query string. + + Exactly one of ``query`` and ``prepared_query`` is + required. Setting both or neither is an + ``INVALID_ARGUMENT``. + This corresponds to the ``query`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1850,8 +2102,10 @@ def execute_query( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: Iterable[google.cloud.bigtable_v2.types.ExecuteQueryResponse]: @@ -1862,7 +2116,10 @@ def execute_query( # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([instance_name, query, app_profile_id]) + flattened_params = [instance_name, query, app_profile_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1893,8 +2150,7 @@ def execute_query( if regex_match and regex_match.group("name"): header_params["name"] = regex_match.group("name") - if request.app_profile_id is not None: - # execute_query currently requires empty header support. TODO: remove after support is adde + if request.app_profile_id: header_params["app_profile_id"] = request.app_profile_id if header_params: diff --git a/google/cloud/bigtable_v2/services/bigtable/transports/base.py b/google/cloud/bigtable_v2/services/bigtable/transports/base.py index 17ff3fb3d..72d063828 100644 --- a/google/cloud/bigtable_v2/services/bigtable/transports/base.py +++ b/google/cloud/bigtable_v2/services/bigtable/transports/base.py @@ -191,9 +191,24 @@ def _prep_wrapped_messages(self, client_info): default_timeout=43200.0, client_info=client_info, ), + self.prepare_query: gapic_v1.method.wrap_method( + self.prepare_query, + default_timeout=None, + client_info=client_info, + ), self.execute_query: gapic_v1.method.wrap_method( self.execute_query, - default_timeout=None, + default_retry=retries.Retry( + initial=0.01, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=43200.0, + ), + default_timeout=43200.0, client_info=client_info, ), } @@ -302,6 +317,15 @@ def read_change_stream( ]: raise NotImplementedError() + @property + def prepare_query( + self, + ) -> Callable[ + [bigtable.PrepareQueryRequest], + Union[bigtable.PrepareQueryResponse, Awaitable[bigtable.PrepareQueryResponse]], + ]: + raise NotImplementedError() + @property def execute_query( self, diff --git a/google/cloud/bigtable_v2/services/bigtable/transports/grpc.py b/google/cloud/bigtable_v2/services/bigtable/transports/grpc.py index febdd441d..84bc1dd43 100644 --- a/google/cloud/bigtable_v2/services/bigtable/transports/grpc.py +++ b/google/cloud/bigtable_v2/services/bigtable/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union @@ -21,12 +24,90 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message import grpc # type: ignore +import proto # type: ignore from google.cloud.bigtable_v2.types import bigtable from .base import BigtableTransport, DEFAULT_CLIENT_INFO +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class BigtableGrpcTransport(BigtableTransport): """gRPC backend transport for Bigtable. @@ -181,7 +262,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod @@ -260,7 +346,7 @@ def read_rows( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "read_rows" not in self._stubs: - self._stubs["read_rows"] = self.grpc_channel.unary_stream( + self._stubs["read_rows"] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/ReadRows", request_serializer=bigtable.ReadRowsRequest.serialize, response_deserializer=bigtable.ReadRowsResponse.deserialize, @@ -290,7 +376,7 @@ def sample_row_keys( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "sample_row_keys" not in self._stubs: - self._stubs["sample_row_keys"] = self.grpc_channel.unary_stream( + self._stubs["sample_row_keys"] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/SampleRowKeys", request_serializer=bigtable.SampleRowKeysRequest.serialize, response_deserializer=bigtable.SampleRowKeysResponse.deserialize, @@ -317,7 +403,7 @@ def mutate_row( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "mutate_row" not in self._stubs: - self._stubs["mutate_row"] = self.grpc_channel.unary_unary( + self._stubs["mutate_row"] = self._logged_channel.unary_unary( "/google.bigtable.v2.Bigtable/MutateRow", request_serializer=bigtable.MutateRowRequest.serialize, response_deserializer=bigtable.MutateRowResponse.deserialize, @@ -345,7 +431,7 @@ def mutate_rows( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "mutate_rows" not in self._stubs: - self._stubs["mutate_rows"] = self.grpc_channel.unary_stream( + self._stubs["mutate_rows"] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/MutateRows", request_serializer=bigtable.MutateRowsRequest.serialize, response_deserializer=bigtable.MutateRowsResponse.deserialize, @@ -374,7 +460,7 @@ def check_and_mutate_row( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "check_and_mutate_row" not in self._stubs: - self._stubs["check_and_mutate_row"] = self.grpc_channel.unary_unary( + self._stubs["check_and_mutate_row"] = self._logged_channel.unary_unary( "/google.bigtable.v2.Bigtable/CheckAndMutateRow", request_serializer=bigtable.CheckAndMutateRowRequest.serialize, response_deserializer=bigtable.CheckAndMutateRowResponse.deserialize, @@ -402,7 +488,7 @@ def ping_and_warm( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "ping_and_warm" not in self._stubs: - self._stubs["ping_and_warm"] = self.grpc_channel.unary_unary( + self._stubs["ping_and_warm"] = self._logged_channel.unary_unary( "/google.bigtable.v2.Bigtable/PingAndWarm", request_serializer=bigtable.PingAndWarmRequest.serialize, response_deserializer=bigtable.PingAndWarmResponse.deserialize, @@ -436,7 +522,7 @@ def read_modify_write_row( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "read_modify_write_row" not in self._stubs: - self._stubs["read_modify_write_row"] = self.grpc_channel.unary_unary( + self._stubs["read_modify_write_row"] = self._logged_channel.unary_unary( "/google.bigtable.v2.Bigtable/ReadModifyWriteRow", request_serializer=bigtable.ReadModifyWriteRowRequest.serialize, response_deserializer=bigtable.ReadModifyWriteRowResponse.deserialize, @@ -471,7 +557,7 @@ def generate_initial_change_stream_partitions( if "generate_initial_change_stream_partitions" not in self._stubs: self._stubs[ "generate_initial_change_stream_partitions" - ] = self.grpc_channel.unary_stream( + ] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/GenerateInitialChangeStreamPartitions", request_serializer=bigtable.GenerateInitialChangeStreamPartitionsRequest.serialize, response_deserializer=bigtable.GenerateInitialChangeStreamPartitionsResponse.deserialize, @@ -502,21 +588,48 @@ def read_change_stream( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "read_change_stream" not in self._stubs: - self._stubs["read_change_stream"] = self.grpc_channel.unary_stream( + self._stubs["read_change_stream"] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/ReadChangeStream", request_serializer=bigtable.ReadChangeStreamRequest.serialize, response_deserializer=bigtable.ReadChangeStreamResponse.deserialize, ) return self._stubs["read_change_stream"] + @property + def prepare_query( + self, + ) -> Callable[[bigtable.PrepareQueryRequest], bigtable.PrepareQueryResponse]: + r"""Return a callable for the prepare query method over gRPC. + + Prepares a GoogleSQL query for execution on a + particular Bigtable instance. + + Returns: + Callable[[~.PrepareQueryRequest], + ~.PrepareQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "prepare_query" not in self._stubs: + self._stubs["prepare_query"] = self._logged_channel.unary_unary( + "/google.bigtable.v2.Bigtable/PrepareQuery", + request_serializer=bigtable.PrepareQueryRequest.serialize, + response_deserializer=bigtable.PrepareQueryResponse.deserialize, + ) + return self._stubs["prepare_query"] + @property def execute_query( self, ) -> Callable[[bigtable.ExecuteQueryRequest], bigtable.ExecuteQueryResponse]: r"""Return a callable for the execute query method over gRPC. - Executes a BTQL query against a particular Cloud - Bigtable instance. + Executes a SQL query against a particular Bigtable + instance. Returns: Callable[[~.ExecuteQueryRequest], @@ -529,7 +642,7 @@ def execute_query( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "execute_query" not in self._stubs: - self._stubs["execute_query"] = self.grpc_channel.unary_stream( + self._stubs["execute_query"] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/ExecuteQuery", request_serializer=bigtable.ExecuteQueryRequest.serialize, response_deserializer=bigtable.ExecuteQueryResponse.deserialize, @@ -537,7 +650,7 @@ def execute_query( return self._stubs["execute_query"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def kind(self) -> str: diff --git a/google/cloud/bigtable_v2/services/bigtable/transports/grpc_asyncio.py b/google/cloud/bigtable_v2/services/bigtable/transports/grpc_asyncio.py index 6f6e1fe85..192ce8281 100644 --- a/google/cloud/bigtable_v2/services/bigtable/transports/grpc_asyncio.py +++ b/google/cloud/bigtable_v2/services/bigtable/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import pickle +import logging as std_logging import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union @@ -23,14 +26,93 @@ from google.api_core import retry_async as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.bigtable_v2.types import bigtable from .base import BigtableTransport, DEFAULT_CLIENT_INFO from .grpc import BigtableGrpcTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class BigtableGrpcAsyncIOTransport(BigtableTransport): """gRPC AsyncIO backend transport for Bigtable. @@ -228,10 +310,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel self._wrap_with_kind = ( "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters ) + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @property @@ -268,7 +353,7 @@ def read_rows( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "read_rows" not in self._stubs: - self._stubs["read_rows"] = self.grpc_channel.unary_stream( + self._stubs["read_rows"] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/ReadRows", request_serializer=bigtable.ReadRowsRequest.serialize, response_deserializer=bigtable.ReadRowsResponse.deserialize, @@ -300,7 +385,7 @@ def sample_row_keys( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "sample_row_keys" not in self._stubs: - self._stubs["sample_row_keys"] = self.grpc_channel.unary_stream( + self._stubs["sample_row_keys"] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/SampleRowKeys", request_serializer=bigtable.SampleRowKeysRequest.serialize, response_deserializer=bigtable.SampleRowKeysResponse.deserialize, @@ -327,7 +412,7 @@ def mutate_row( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "mutate_row" not in self._stubs: - self._stubs["mutate_row"] = self.grpc_channel.unary_unary( + self._stubs["mutate_row"] = self._logged_channel.unary_unary( "/google.bigtable.v2.Bigtable/MutateRow", request_serializer=bigtable.MutateRowRequest.serialize, response_deserializer=bigtable.MutateRowResponse.deserialize, @@ -355,7 +440,7 @@ def mutate_rows( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "mutate_rows" not in self._stubs: - self._stubs["mutate_rows"] = self.grpc_channel.unary_stream( + self._stubs["mutate_rows"] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/MutateRows", request_serializer=bigtable.MutateRowsRequest.serialize, response_deserializer=bigtable.MutateRowsResponse.deserialize, @@ -385,7 +470,7 @@ def check_and_mutate_row( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "check_and_mutate_row" not in self._stubs: - self._stubs["check_and_mutate_row"] = self.grpc_channel.unary_unary( + self._stubs["check_and_mutate_row"] = self._logged_channel.unary_unary( "/google.bigtable.v2.Bigtable/CheckAndMutateRow", request_serializer=bigtable.CheckAndMutateRowRequest.serialize, response_deserializer=bigtable.CheckAndMutateRowResponse.deserialize, @@ -415,7 +500,7 @@ def ping_and_warm( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "ping_and_warm" not in self._stubs: - self._stubs["ping_and_warm"] = self.grpc_channel.unary_unary( + self._stubs["ping_and_warm"] = self._logged_channel.unary_unary( "/google.bigtable.v2.Bigtable/PingAndWarm", request_serializer=bigtable.PingAndWarmRequest.serialize, response_deserializer=bigtable.PingAndWarmResponse.deserialize, @@ -450,7 +535,7 @@ def read_modify_write_row( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "read_modify_write_row" not in self._stubs: - self._stubs["read_modify_write_row"] = self.grpc_channel.unary_unary( + self._stubs["read_modify_write_row"] = self._logged_channel.unary_unary( "/google.bigtable.v2.Bigtable/ReadModifyWriteRow", request_serializer=bigtable.ReadModifyWriteRowRequest.serialize, response_deserializer=bigtable.ReadModifyWriteRowResponse.deserialize, @@ -485,7 +570,7 @@ def generate_initial_change_stream_partitions( if "generate_initial_change_stream_partitions" not in self._stubs: self._stubs[ "generate_initial_change_stream_partitions" - ] = self.grpc_channel.unary_stream( + ] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/GenerateInitialChangeStreamPartitions", request_serializer=bigtable.GenerateInitialChangeStreamPartitionsRequest.serialize, response_deserializer=bigtable.GenerateInitialChangeStreamPartitionsResponse.deserialize, @@ -516,13 +601,42 @@ def read_change_stream( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "read_change_stream" not in self._stubs: - self._stubs["read_change_stream"] = self.grpc_channel.unary_stream( + self._stubs["read_change_stream"] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/ReadChangeStream", request_serializer=bigtable.ReadChangeStreamRequest.serialize, response_deserializer=bigtable.ReadChangeStreamResponse.deserialize, ) return self._stubs["read_change_stream"] + @property + def prepare_query( + self, + ) -> Callable[ + [bigtable.PrepareQueryRequest], Awaitable[bigtable.PrepareQueryResponse] + ]: + r"""Return a callable for the prepare query method over gRPC. + + Prepares a GoogleSQL query for execution on a + particular Bigtable instance. + + Returns: + Callable[[~.PrepareQueryRequest], + Awaitable[~.PrepareQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "prepare_query" not in self._stubs: + self._stubs["prepare_query"] = self._logged_channel.unary_unary( + "/google.bigtable.v2.Bigtable/PrepareQuery", + request_serializer=bigtable.PrepareQueryRequest.serialize, + response_deserializer=bigtable.PrepareQueryResponse.deserialize, + ) + return self._stubs["prepare_query"] + @property def execute_query( self, @@ -531,8 +645,8 @@ def execute_query( ]: r"""Return a callable for the execute query method over gRPC. - Executes a BTQL query against a particular Cloud - Bigtable instance. + Executes a SQL query against a particular Bigtable + instance. Returns: Callable[[~.ExecuteQueryRequest], @@ -545,7 +659,7 @@ def execute_query( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "execute_query" not in self._stubs: - self._stubs["execute_query"] = self.grpc_channel.unary_stream( + self._stubs["execute_query"] = self._logged_channel.unary_stream( "/google.bigtable.v2.Bigtable/ExecuteQuery", request_serializer=bigtable.ExecuteQueryRequest.serialize, response_deserializer=bigtable.ExecuteQueryResponse.deserialize, @@ -610,9 +724,24 @@ def _prep_wrapped_messages(self, client_info): default_timeout=43200.0, client_info=client_info, ), + self.prepare_query: self._wrap_method( + self.prepare_query, + default_timeout=None, + client_info=client_info, + ), self.execute_query: self._wrap_method( self.execute_query, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=0.01, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=43200.0, + ), + default_timeout=43200.0, client_info=client_info, ), } @@ -623,7 +752,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: diff --git a/google/cloud/bigtable_v2/services/bigtable/transports/rest.py b/google/cloud/bigtable_v2/services/bigtable/transports/rest.py index 221b04b8a..fb0af2af9 100644 --- a/google/cloud/bigtable_v2/services/bigtable/transports/rest.py +++ b/google/cloud/bigtable_v2/services/bigtable/transports/rest.py @@ -13,9 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import logging +import json # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries @@ -42,6 +43,14 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -113,6 +122,14 @@ def post_ping_and_warm(self, response): logging.log(f"Received response: {response}") return response + def pre_prepare_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_prepare_query(self, response): + logging.log(f"Received response: {response}") + return response + def pre_read_change_stream(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -154,8 +171,10 @@ def post_sample_row_keys(self, response): def pre_check_and_mutate_row( self, request: bigtable.CheckAndMutateRowRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable.CheckAndMutateRowRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable.CheckAndMutateRowRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for check_and_mutate_row Override in a subclass to manipulate the request or metadata @@ -168,15 +187,42 @@ def post_check_and_mutate_row( ) -> bigtable.CheckAndMutateRowResponse: """Post-rpc interceptor for check_and_mutate_row - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_check_and_mutate_row_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Bigtable server but before - it is returned to user code. + it is returned to user code. This `post_check_and_mutate_row` interceptor runs + before the `post_check_and_mutate_row_with_metadata` interceptor. """ return response + def post_check_and_mutate_row_with_metadata( + self, + response: bigtable.CheckAndMutateRowResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable.CheckAndMutateRowResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for check_and_mutate_row + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_check_and_mutate_row_with_metadata` + interceptor in new development instead of the `post_check_and_mutate_row` interceptor. + When both interceptors are used, this `post_check_and_mutate_row_with_metadata` interceptor runs after the + `post_check_and_mutate_row` interceptor. The (possibly modified) response returned by + `post_check_and_mutate_row` will be passed to + `post_check_and_mutate_row_with_metadata`. + """ + return response, metadata + def pre_execute_query( - self, request: bigtable.ExecuteQueryRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[bigtable.ExecuteQueryRequest, Sequence[Tuple[str, str]]]: + self, + request: bigtable.ExecuteQueryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[bigtable.ExecuteQueryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for execute_query Override in a subclass to manipulate the request or metadata @@ -189,18 +235,44 @@ def post_execute_query( ) -> rest_streaming.ResponseIterator: """Post-rpc interceptor for execute_query - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_execute_query_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Bigtable server but before - it is returned to user code. + it is returned to user code. This `post_execute_query` interceptor runs + before the `post_execute_query_with_metadata` interceptor. """ return response + def post_execute_query_with_metadata( + self, + response: rest_streaming.ResponseIterator, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for execute_query + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_execute_query_with_metadata` + interceptor in new development instead of the `post_execute_query` interceptor. + When both interceptors are used, this `post_execute_query_with_metadata` interceptor runs after the + `post_execute_query` interceptor. The (possibly modified) response returned by + `post_execute_query` will be passed to + `post_execute_query_with_metadata`. + """ + return response, metadata + def pre_generate_initial_change_stream_partitions( self, request: bigtable.GenerateInitialChangeStreamPartitionsRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - bigtable.GenerateInitialChangeStreamPartitionsRequest, Sequence[Tuple[str, str]] + bigtable.GenerateInitialChangeStreamPartitionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for generate_initial_change_stream_partitions @@ -214,15 +286,42 @@ def post_generate_initial_change_stream_partitions( ) -> rest_streaming.ResponseIterator: """Post-rpc interceptor for generate_initial_change_stream_partitions - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_generate_initial_change_stream_partitions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Bigtable server but before - it is returned to user code. + it is returned to user code. This `post_generate_initial_change_stream_partitions` interceptor runs + before the `post_generate_initial_change_stream_partitions_with_metadata` interceptor. """ return response + def post_generate_initial_change_stream_partitions_with_metadata( + self, + response: rest_streaming.ResponseIterator, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for generate_initial_change_stream_partitions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_generate_initial_change_stream_partitions_with_metadata` + interceptor in new development instead of the `post_generate_initial_change_stream_partitions` interceptor. + When both interceptors are used, this `post_generate_initial_change_stream_partitions_with_metadata` interceptor runs after the + `post_generate_initial_change_stream_partitions` interceptor. The (possibly modified) response returned by + `post_generate_initial_change_stream_partitions` will be passed to + `post_generate_initial_change_stream_partitions_with_metadata`. + """ + return response, metadata + def pre_mutate_row( - self, request: bigtable.MutateRowRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[bigtable.MutateRowRequest, Sequence[Tuple[str, str]]]: + self, + request: bigtable.MutateRowRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[bigtable.MutateRowRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for mutate_row Override in a subclass to manipulate the request or metadata @@ -235,15 +334,40 @@ def post_mutate_row( ) -> bigtable.MutateRowResponse: """Post-rpc interceptor for mutate_row - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_mutate_row_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Bigtable server but before - it is returned to user code. + it is returned to user code. This `post_mutate_row` interceptor runs + before the `post_mutate_row_with_metadata` interceptor. """ return response + def post_mutate_row_with_metadata( + self, + response: bigtable.MutateRowResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[bigtable.MutateRowResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for mutate_row + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_mutate_row_with_metadata` + interceptor in new development instead of the `post_mutate_row` interceptor. + When both interceptors are used, this `post_mutate_row_with_metadata` interceptor runs after the + `post_mutate_row` interceptor. The (possibly modified) response returned by + `post_mutate_row` will be passed to + `post_mutate_row_with_metadata`. + """ + return response, metadata + def pre_mutate_rows( - self, request: bigtable.MutateRowsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[bigtable.MutateRowsRequest, Sequence[Tuple[str, str]]]: + self, + request: bigtable.MutateRowsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[bigtable.MutateRowsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for mutate_rows Override in a subclass to manipulate the request or metadata @@ -256,15 +380,42 @@ def post_mutate_rows( ) -> rest_streaming.ResponseIterator: """Post-rpc interceptor for mutate_rows - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_mutate_rows_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Bigtable server but before - it is returned to user code. + it is returned to user code. This `post_mutate_rows` interceptor runs + before the `post_mutate_rows_with_metadata` interceptor. """ return response + def post_mutate_rows_with_metadata( + self, + response: rest_streaming.ResponseIterator, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for mutate_rows + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_mutate_rows_with_metadata` + interceptor in new development instead of the `post_mutate_rows` interceptor. + When both interceptors are used, this `post_mutate_rows_with_metadata` interceptor runs after the + `post_mutate_rows` interceptor. The (possibly modified) response returned by + `post_mutate_rows` will be passed to + `post_mutate_rows_with_metadata`. + """ + return response, metadata + def pre_ping_and_warm( - self, request: bigtable.PingAndWarmRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[bigtable.PingAndWarmRequest, Sequence[Tuple[str, str]]]: + self, + request: bigtable.PingAndWarmRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[bigtable.PingAndWarmRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for ping_and_warm Override in a subclass to manipulate the request or metadata @@ -277,17 +428,88 @@ def post_ping_and_warm( ) -> bigtable.PingAndWarmResponse: """Post-rpc interceptor for ping_and_warm - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_ping_and_warm_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Bigtable server but before - it is returned to user code. + it is returned to user code. This `post_ping_and_warm` interceptor runs + before the `post_ping_and_warm_with_metadata` interceptor. """ return response + def post_ping_and_warm_with_metadata( + self, + response: bigtable.PingAndWarmResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[bigtable.PingAndWarmResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for ping_and_warm + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_ping_and_warm_with_metadata` + interceptor in new development instead of the `post_ping_and_warm` interceptor. + When both interceptors are used, this `post_ping_and_warm_with_metadata` interceptor runs after the + `post_ping_and_warm` interceptor. The (possibly modified) response returned by + `post_ping_and_warm` will be passed to + `post_ping_and_warm_with_metadata`. + """ + return response, metadata + + def pre_prepare_query( + self, + request: bigtable.PrepareQueryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[bigtable.PrepareQueryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for prepare_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the Bigtable server. + """ + return request, metadata + + def post_prepare_query( + self, response: bigtable.PrepareQueryResponse + ) -> bigtable.PrepareQueryResponse: + """Post-rpc interceptor for prepare_query + + DEPRECATED. Please use the `post_prepare_query_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Bigtable server but before + it is returned to user code. This `post_prepare_query` interceptor runs + before the `post_prepare_query_with_metadata` interceptor. + """ + return response + + def post_prepare_query_with_metadata( + self, + response: bigtable.PrepareQueryResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[bigtable.PrepareQueryResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for prepare_query + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_prepare_query_with_metadata` + interceptor in new development instead of the `post_prepare_query` interceptor. + When both interceptors are used, this `post_prepare_query_with_metadata` interceptor runs after the + `post_prepare_query` interceptor. The (possibly modified) response returned by + `post_prepare_query` will be passed to + `post_prepare_query_with_metadata`. + """ + return response, metadata + def pre_read_change_stream( self, request: bigtable.ReadChangeStreamRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable.ReadChangeStreamRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable.ReadChangeStreamRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for read_change_stream Override in a subclass to manipulate the request or metadata @@ -300,17 +522,44 @@ def post_read_change_stream( ) -> rest_streaming.ResponseIterator: """Post-rpc interceptor for read_change_stream - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_read_change_stream_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Bigtable server but before - it is returned to user code. + it is returned to user code. This `post_read_change_stream` interceptor runs + before the `post_read_change_stream_with_metadata` interceptor. """ return response + def post_read_change_stream_with_metadata( + self, + response: rest_streaming.ResponseIterator, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for read_change_stream + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_read_change_stream_with_metadata` + interceptor in new development instead of the `post_read_change_stream` interceptor. + When both interceptors are used, this `post_read_change_stream_with_metadata` interceptor runs after the + `post_read_change_stream` interceptor. The (possibly modified) response returned by + `post_read_change_stream` will be passed to + `post_read_change_stream_with_metadata`. + """ + return response, metadata + def pre_read_modify_write_row( self, request: bigtable.ReadModifyWriteRowRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable.ReadModifyWriteRowRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable.ReadModifyWriteRowRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for read_modify_write_row Override in a subclass to manipulate the request or metadata @@ -323,15 +572,42 @@ def post_read_modify_write_row( ) -> bigtable.ReadModifyWriteRowResponse: """Post-rpc interceptor for read_modify_write_row - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_read_modify_write_row_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Bigtable server but before - it is returned to user code. + it is returned to user code. This `post_read_modify_write_row` interceptor runs + before the `post_read_modify_write_row_with_metadata` interceptor. """ return response + def post_read_modify_write_row_with_metadata( + self, + response: bigtable.ReadModifyWriteRowResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable.ReadModifyWriteRowResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for read_modify_write_row + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_read_modify_write_row_with_metadata` + interceptor in new development instead of the `post_read_modify_write_row` interceptor. + When both interceptors are used, this `post_read_modify_write_row_with_metadata` interceptor runs after the + `post_read_modify_write_row` interceptor. The (possibly modified) response returned by + `post_read_modify_write_row` will be passed to + `post_read_modify_write_row_with_metadata`. + """ + return response, metadata + def pre_read_rows( - self, request: bigtable.ReadRowsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[bigtable.ReadRowsRequest, Sequence[Tuple[str, str]]]: + self, + request: bigtable.ReadRowsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[bigtable.ReadRowsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for read_rows Override in a subclass to manipulate the request or metadata @@ -344,17 +620,42 @@ def post_read_rows( ) -> rest_streaming.ResponseIterator: """Post-rpc interceptor for read_rows - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_read_rows_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Bigtable server but before - it is returned to user code. + it is returned to user code. This `post_read_rows` interceptor runs + before the `post_read_rows_with_metadata` interceptor. """ return response + def post_read_rows_with_metadata( + self, + response: rest_streaming.ResponseIterator, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for read_rows + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_read_rows_with_metadata` + interceptor in new development instead of the `post_read_rows` interceptor. + When both interceptors are used, this `post_read_rows_with_metadata` interceptor runs after the + `post_read_rows` interceptor. The (possibly modified) response returned by + `post_read_rows` will be passed to + `post_read_rows_with_metadata`. + """ + return response, metadata + def pre_sample_row_keys( self, request: bigtable.SampleRowKeysRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[bigtable.SampleRowKeysRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[bigtable.SampleRowKeysRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for sample_row_keys Override in a subclass to manipulate the request or metadata @@ -367,12 +668,37 @@ def post_sample_row_keys( ) -> rest_streaming.ResponseIterator: """Post-rpc interceptor for sample_row_keys - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_sample_row_keys_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Bigtable server but before - it is returned to user code. + it is returned to user code. This `post_sample_row_keys` interceptor runs + before the `post_sample_row_keys_with_metadata` interceptor. """ return response + def post_sample_row_keys_with_metadata( + self, + response: rest_streaming.ResponseIterator, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for sample_row_keys + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Bigtable server but before it is returned to user code. + + We recommend only using this `post_sample_row_keys_with_metadata` + interceptor in new development instead of the `post_sample_row_keys` interceptor. + When both interceptors are used, this `post_sample_row_keys_with_metadata` interceptor runs after the + `post_sample_row_keys` interceptor. The (possibly modified) response returned by + `post_sample_row_keys` will be passed to + `post_sample_row_keys_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class BigtableRestStub: @@ -496,7 +822,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.CheckAndMutateRowResponse: r"""Call the check and mutate row method over HTTP. @@ -507,8 +833,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable.CheckAndMutateRowResponse: @@ -520,6 +848,7 @@ def __call__( http_options = ( _BaseBigtableRestTransport._BaseCheckAndMutateRow._get_http_options() ) + request, metadata = self._interceptor.pre_check_and_mutate_row( request, metadata ) @@ -536,6 +865,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.CheckAndMutateRow", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "CheckAndMutateRow", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableRestTransport._CheckAndMutateRow._get_response( self._host, @@ -557,7 +913,35 @@ def __call__( pb_resp = bigtable.CheckAndMutateRowResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_check_and_mutate_row(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_check_and_mutate_row_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = bigtable.CheckAndMutateRowResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable_v2.BigtableClient.check_and_mutate_row", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "CheckAndMutateRow", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ExecuteQuery(_BaseBigtableRestTransport._BaseExecuteQuery, BigtableRestStub): @@ -594,7 +978,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> rest_streaming.ResponseIterator: r"""Call the execute query method over HTTP. @@ -605,8 +989,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable.ExecuteQueryResponse: @@ -618,6 +1004,7 @@ def __call__( http_options = ( _BaseBigtableRestTransport._BaseExecuteQuery._get_http_options() ) + request, metadata = self._interceptor.pre_execute_query(request, metadata) transcoded_request = ( _BaseBigtableRestTransport._BaseExecuteQuery._get_transcoded_request( @@ -636,6 +1023,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.ExecuteQuery", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "ExecuteQuery", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableRestTransport._ExecuteQuery._get_response( self._host, @@ -656,7 +1070,12 @@ def __call__( resp = rest_streaming.ResponseIterator( response, bigtable.ExecuteQueryResponse ) + resp = self._interceptor.post_execute_query(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_execute_query_with_metadata( + resp, response_metadata + ) return resp class _GenerateInitialChangeStreamPartitions( @@ -696,7 +1115,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> rest_streaming.ResponseIterator: r"""Call the generate initial change stream partitions method over HTTP. @@ -710,8 +1129,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable.GenerateInitialChangeStreamPartitionsResponse: @@ -725,6 +1146,7 @@ def __call__( http_options = ( _BaseBigtableRestTransport._BaseGenerateInitialChangeStreamPartitions._get_http_options() ) + ( request, metadata, @@ -744,6 +1166,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.GenerateInitialChangeStreamPartitions", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "GenerateInitialChangeStreamPartitions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableRestTransport._GenerateInitialChangeStreamPartitions._get_response( self._host, @@ -764,9 +1213,17 @@ def __call__( resp = rest_streaming.ResponseIterator( response, bigtable.GenerateInitialChangeStreamPartitionsResponse ) + resp = self._interceptor.post_generate_initial_change_stream_partitions( resp ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_generate_initial_change_stream_partitions_with_metadata( + resp, response_metadata + ) return resp class _MutateRow(_BaseBigtableRestTransport._BaseMutateRow, BigtableRestStub): @@ -802,7 +1259,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.MutateRowResponse: r"""Call the mutate row method over HTTP. @@ -813,8 +1270,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable.MutateRowResponse: @@ -824,6 +1283,7 @@ def __call__( """ http_options = _BaseBigtableRestTransport._BaseMutateRow._get_http_options() + request, metadata = self._interceptor.pre_mutate_row(request, metadata) transcoded_request = ( _BaseBigtableRestTransport._BaseMutateRow._get_transcoded_request( @@ -842,6 +1302,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.MutateRow", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "MutateRow", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableRestTransport._MutateRow._get_response( self._host, @@ -863,7 +1350,33 @@ def __call__( pb_resp = bigtable.MutateRowResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_mutate_row(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_mutate_row_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = bigtable.MutateRowResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable_v2.BigtableClient.mutate_row", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "MutateRow", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _MutateRows(_BaseBigtableRestTransport._BaseMutateRows, BigtableRestStub): @@ -900,7 +1413,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> rest_streaming.ResponseIterator: r"""Call the mutate rows method over HTTP. @@ -911,8 +1424,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable.MutateRowsResponse: @@ -924,6 +1439,7 @@ def __call__( http_options = ( _BaseBigtableRestTransport._BaseMutateRows._get_http_options() ) + request, metadata = self._interceptor.pre_mutate_rows(request, metadata) transcoded_request = ( _BaseBigtableRestTransport._BaseMutateRows._get_transcoded_request( @@ -942,6 +1458,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.MutateRows", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "MutateRows", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableRestTransport._MutateRows._get_response( self._host, @@ -962,7 +1505,12 @@ def __call__( resp = rest_streaming.ResponseIterator( response, bigtable.MutateRowsResponse ) + resp = self._interceptor.post_mutate_rows(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_mutate_rows_with_metadata( + resp, response_metadata + ) return resp class _PingAndWarm(_BaseBigtableRestTransport._BasePingAndWarm, BigtableRestStub): @@ -998,7 +1546,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.PingAndWarmResponse: r"""Call the ping and warm method over HTTP. @@ -1009,8 +1557,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable.PingAndWarmResponse: @@ -1023,6 +1573,7 @@ def __call__( http_options = ( _BaseBigtableRestTransport._BasePingAndWarm._get_http_options() ) + request, metadata = self._interceptor.pre_ping_and_warm(request, metadata) transcoded_request = ( _BaseBigtableRestTransport._BasePingAndWarm._get_transcoded_request( @@ -1041,6 +1592,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.PingAndWarm", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "PingAndWarm", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableRestTransport._PingAndWarm._get_response( self._host, @@ -1062,7 +1640,188 @@ def __call__( pb_resp = bigtable.PingAndWarmResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_ping_and_warm(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_ping_and_warm_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = bigtable.PingAndWarmResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable_v2.BigtableClient.ping_and_warm", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "PingAndWarm", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PrepareQuery(_BaseBigtableRestTransport._BasePrepareQuery, BigtableRestStub): + def __hash__(self): + return hash("BigtableRestTransport.PrepareQuery") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: bigtable.PrepareQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> bigtable.PrepareQueryResponse: + r"""Call the prepare query method over HTTP. + + Args: + request (~.bigtable.PrepareQueryRequest): + The request object. Request message for + Bigtable.PrepareQuery + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.bigtable.PrepareQueryResponse: + Response message for + Bigtable.PrepareQueryResponse + + """ + + http_options = ( + _BaseBigtableRestTransport._BasePrepareQuery._get_http_options() + ) + + request, metadata = self._interceptor.pre_prepare_query(request, metadata) + transcoded_request = ( + _BaseBigtableRestTransport._BasePrepareQuery._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseBigtableRestTransport._BasePrepareQuery._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseBigtableRestTransport._BasePrepareQuery._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.PrepareQuery", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "PrepareQuery", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BigtableRestTransport._PrepareQuery._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigtable.PrepareQueryResponse() + pb_resp = bigtable.PrepareQueryResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_prepare_query(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_prepare_query_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = bigtable.PrepareQueryResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable_v2.BigtableClient.prepare_query", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "PrepareQuery", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ReadChangeStream( @@ -1101,7 +1860,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> rest_streaming.ResponseIterator: r"""Call the read change stream method over HTTP. @@ -1113,8 +1872,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable.ReadChangeStreamResponse: @@ -1127,6 +1888,7 @@ def __call__( http_options = ( _BaseBigtableRestTransport._BaseReadChangeStream._get_http_options() ) + request, metadata = self._interceptor.pre_read_change_stream( request, metadata ) @@ -1147,6 +1909,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.ReadChangeStream", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "ReadChangeStream", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableRestTransport._ReadChangeStream._get_response( self._host, @@ -1167,7 +1956,12 @@ def __call__( resp = rest_streaming.ResponseIterator( response, bigtable.ReadChangeStreamResponse ) + resp = self._interceptor.post_read_change_stream(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_read_change_stream_with_metadata( + resp, response_metadata + ) return resp class _ReadModifyWriteRow( @@ -1205,7 +1999,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bigtable.ReadModifyWriteRowResponse: r"""Call the read modify write row method over HTTP. @@ -1216,8 +2010,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable.ReadModifyWriteRowResponse: @@ -1229,6 +2025,7 @@ def __call__( http_options = ( _BaseBigtableRestTransport._BaseReadModifyWriteRow._get_http_options() ) + request, metadata = self._interceptor.pre_read_modify_write_row( request, metadata ) @@ -1245,6 +2042,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.ReadModifyWriteRow", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "ReadModifyWriteRow", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableRestTransport._ReadModifyWriteRow._get_response( self._host, @@ -1266,7 +2090,35 @@ def __call__( pb_resp = bigtable.ReadModifyWriteRowResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_read_modify_write_row(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_read_modify_write_row_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = bigtable.ReadModifyWriteRowResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable_v2.BigtableClient.read_modify_write_row", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "ReadModifyWriteRow", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ReadRows(_BaseBigtableRestTransport._BaseReadRows, BigtableRestStub): @@ -1303,7 +2155,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> rest_streaming.ResponseIterator: r"""Call the read rows method over HTTP. @@ -1314,8 +2166,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable.ReadRowsResponse: @@ -1325,6 +2179,7 @@ def __call__( """ http_options = _BaseBigtableRestTransport._BaseReadRows._get_http_options() + request, metadata = self._interceptor.pre_read_rows(request, metadata) transcoded_request = ( _BaseBigtableRestTransport._BaseReadRows._get_transcoded_request( @@ -1343,6 +2198,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.ReadRows", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "ReadRows", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableRestTransport._ReadRows._get_response( self._host, @@ -1361,7 +2243,12 @@ def __call__( # Return the response resp = rest_streaming.ResponseIterator(response, bigtable.ReadRowsResponse) + resp = self._interceptor.post_read_rows(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_read_rows_with_metadata( + resp, response_metadata + ) return resp class _SampleRowKeys( @@ -1399,7 +2286,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> rest_streaming.ResponseIterator: r"""Call the sample row keys method over HTTP. @@ -1410,8 +2297,10 @@ def __call__( retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.bigtable.SampleRowKeysResponse: @@ -1423,6 +2312,7 @@ def __call__( http_options = ( _BaseBigtableRestTransport._BaseSampleRowKeys._get_http_options() ) + request, metadata = self._interceptor.pre_sample_row_keys(request, metadata) transcoded_request = ( _BaseBigtableRestTransport._BaseSampleRowKeys._get_transcoded_request( @@ -1437,6 +2327,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable_v2.BigtableClient.SampleRowKeys", + extra={ + "serviceName": "google.bigtable.v2.Bigtable", + "rpcName": "SampleRowKeys", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = BigtableRestTransport._SampleRowKeys._get_response( self._host, @@ -1456,7 +2373,12 @@ def __call__( resp = rest_streaming.ResponseIterator( response, bigtable.SampleRowKeysResponse ) + resp = self._interceptor.post_sample_row_keys(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_sample_row_keys_with_metadata( + resp, response_metadata + ) return resp @property @@ -1512,6 +2434,14 @@ def ping_and_warm( # In C++ this would require a dynamic_cast return self._PingAndWarm(self._session, self._host, self._interceptor) # type: ignore + @property + def prepare_query( + self, + ) -> Callable[[bigtable.PrepareQueryRequest], bigtable.PrepareQueryResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PrepareQuery(self._session, self._host, self._interceptor) # type: ignore + @property def read_change_stream( self, diff --git a/google/cloud/bigtable_v2/services/bigtable/transports/rest_base.py b/google/cloud/bigtable_v2/services/bigtable/transports/rest_base.py index 9d2292a3c..c33fc1e83 100644 --- a/google/cloud/bigtable_v2/services/bigtable/transports/rest_base.py +++ b/google/cloud/bigtable_v2/services/bigtable/transports/rest_base.py @@ -448,6 +448,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BasePrepareQuery: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{instance_name=projects/*/instances/*}:prepareQuery", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = bigtable.PrepareQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBigtableRestTransport._BasePrepareQuery._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseReadChangeStream: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/google/cloud/bigtable_v2/types/__init__.py b/google/cloud/bigtable_v2/types/__init__.py index e524627cd..c15a1d307 100644 --- a/google/cloud/bigtable_v2/types/__init__.py +++ b/google/cloud/bigtable_v2/types/__init__.py @@ -26,6 +26,8 @@ MutateRowsResponse, PingAndWarmRequest, PingAndWarmResponse, + PrepareQueryRequest, + PrepareQueryResponse, RateLimitInfo, ReadChangeStreamRequest, ReadChangeStreamResponse, @@ -91,6 +93,8 @@ "MutateRowsResponse", "PingAndWarmRequest", "PingAndWarmResponse", + "PrepareQueryRequest", + "PrepareQueryResponse", "RateLimitInfo", "ReadChangeStreamRequest", "ReadChangeStreamResponse", diff --git a/google/cloud/bigtable_v2/types/bigtable.py b/google/cloud/bigtable_v2/types/bigtable.py index 3818decb6..6d9be1438 100644 --- a/google/cloud/bigtable_v2/types/bigtable.py +++ b/google/cloud/bigtable_v2/types/bigtable.py @@ -21,6 +21,7 @@ from google.cloud.bigtable_v2.types import data from google.cloud.bigtable_v2.types import request_stats as gb_request_stats +from google.cloud.bigtable_v2.types import types from google.protobuf import duration_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore @@ -51,6 +52,8 @@ "ReadChangeStreamResponse", "ExecuteQueryRequest", "ExecuteQueryResponse", + "PrepareQueryRequest", + "PrepareQueryResponse", }, ) @@ -70,6 +73,12 @@ class ReadRowsRequest(proto.Message): Values are of the form ``projects//instances//tables//authorizedViews/``. + materialized_view_name (str): + Optional. The unique name of the MaterializedView from which + to read. + + Values are of the form + ``projects//instances//materializedViews/``. app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application @@ -136,6 +145,10 @@ class RequestStatsView(proto.Enum): proto.STRING, number=9, ) + materialized_view_name: str = proto.Field( + proto.STRING, + number=11, + ) app_profile_id: str = proto.Field( proto.STRING, number=5, @@ -351,6 +364,12 @@ class SampleRowKeysRequest(proto.Message): Values are of the form ``projects//instances//tables/
/authorizedViews/``. + materialized_view_name (str): + Optional. The unique name of the MaterializedView from which + to read. + + Values are of the form + ``projects//instances//materializedViews/``. app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application @@ -365,6 +384,10 @@ class SampleRowKeysRequest(proto.Message): proto.STRING, number=4, ) + materialized_view_name: str = proto.Field( + proto.STRING, + number=5, + ) app_profile_id: str = proto.Field( proto.STRING, number=2, @@ -1276,6 +1299,23 @@ class ExecuteQueryRequest(proto.Message): used. query (str): Required. The query string. + + Exactly one of ``query`` and ``prepared_query`` is required. + Setting both or neither is an ``INVALID_ARGUMENT``. + prepared_query (bytes): + A prepared query that was returned from + ``PrepareQueryResponse``. + + Exactly one of ``query`` and ``prepared_query`` is required. + Setting both or neither is an ``INVALID_ARGUMENT``. + + Setting this field also places restrictions on several other + fields: + + - ``data_format`` must be empty. + - ``validate_only`` must be false. + - ``params`` must match the ``param_types`` set in the + ``PrepareQueryRequest``. proto_format (google.cloud.bigtable_v2.types.ProtoFormat): Protocol buffer format as described by ProtoSchema and ProtoRows messages. @@ -1301,14 +1341,19 @@ class ExecuteQueryRequest(proto.Message): then ``@firstName`` will be replaced with googlesql bytes value "foo" in the query string during query evaluation. - In case of Value.kind is not set, it will be set to - corresponding null value in googlesql. + If ``Value.kind`` is not set, the value is treated as a NULL + value of the given type. For example, if ``params["firstName"] = type {string_type {}}`` then ``@firstName`` will be replaced with googlesql null string. - Value.type should always be set and no inference of type - will be made from Value.kind. If Value.type is not set, we - will return INVALID_ARGUMENT error. + If ``query`` is set, any empty ``Value.type`` in the map + will be rejected with ``INVALID_ARGUMENT``. + + If ``prepared_query`` is set, any empty ``Value.type`` in + the map will be inferred from the ``param_types`` in the + ``PrepareQueryRequest``. Any non-empty ``Value.type`` must + match the corresponding ``param_types`` entry, or be + rejected with ``INVALID_ARGUMENT``. """ instance_name: str = proto.Field( @@ -1323,6 +1368,10 @@ class ExecuteQueryRequest(proto.Message): proto.STRING, number=3, ) + prepared_query: bytes = proto.Field( + proto.BYTES, + number=9, + ) proto_format: data.ProtoFormat = proto.Field( proto.MESSAGE, number=4, @@ -1381,4 +1430,102 @@ class ExecuteQueryResponse(proto.Message): ) +class PrepareQueryRequest(proto.Message): + r"""Request message for Bigtable.PrepareQuery + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_name (str): + Required. The unique name of the instance against which the + query should be executed. Values are of the form + ``projects//instances/`` + app_profile_id (str): + Optional. This value specifies routing for preparing the + query. Note that this ``app_profile_id`` is only used for + preparing the query. The actual query execution will use the + app profile specified in the ``ExecuteQueryRequest``. If not + specified, the ``default`` application profile will be used. + query (str): + Required. The query string. + proto_format (google.cloud.bigtable_v2.types.ProtoFormat): + Protocol buffer format as described by + ProtoSchema and ProtoRows messages. + + This field is a member of `oneof`_ ``data_format``. + param_types (MutableMapping[str, google.cloud.bigtable_v2.types.Type]): + Required. ``param_types`` is a map of parameter identifier + strings to their ``Type``\ s. + + In query string, a parameter placeholder consists of the + ``@`` character followed by the parameter name (for example, + ``@firstName``) in the query string. + + For example, if param_types["firstName"] = Bytes then + @firstName will be a query parameter of type Bytes. The + specific ``Value`` to be used for the query execution must + be sent in ``ExecuteQueryRequest`` in the ``params`` map. + """ + + instance_name: str = proto.Field( + proto.STRING, + number=1, + ) + app_profile_id: str = proto.Field( + proto.STRING, + number=2, + ) + query: str = proto.Field( + proto.STRING, + number=3, + ) + proto_format: data.ProtoFormat = proto.Field( + proto.MESSAGE, + number=4, + oneof="data_format", + message=data.ProtoFormat, + ) + param_types: MutableMapping[str, types.Type] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=6, + message=types.Type, + ) + + +class PrepareQueryResponse(proto.Message): + r"""Response message for Bigtable.PrepareQueryResponse + + Attributes: + metadata (google.cloud.bigtable_v2.types.ResultSetMetadata): + Structure of rows in the response stream of + ``ExecuteQueryResponse`` for the returned + ``prepared_query``. + prepared_query (bytes): + A serialized prepared query. Clients should treat this as an + opaque blob of bytes to send in ``ExecuteQueryRequest``. + valid_until (google.protobuf.timestamp_pb2.Timestamp): + The time at which the prepared query token + becomes invalid. A token may become invalid + early due to changes in the data being read, but + it provides a guideline to refresh query plans + asynchronously. + """ + + metadata: data.ResultSetMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=data.ResultSetMetadata, + ) + prepared_query: bytes = proto.Field( + proto.BYTES, + number=2, + ) + valid_until: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/bigtable_v2/types/data.py b/google/cloud/bigtable_v2/types/data.py index 9d964a4f6..97e32197e 100644 --- a/google/cloud/bigtable_v2/types/data.py +++ b/google/cloud/bigtable_v2/types/data.py @@ -1464,12 +1464,15 @@ class ProtoRows(proto.Message): class ProtoRowsBatch(proto.Message): - r"""Batch of serialized ProtoRows. + r"""A part of a serialized ``ProtoRows`` message. Attributes: batch_data (bytes): - Merge partial results by concatenating these bytes, then - parsing the overall value as a ``ProtoRows`` message. + Part of a serialized ``ProtoRows`` message. A complete, + parseable ProtoRows message is constructed by concatenating + ``batch_data`` from multiple ``ProtoRowsBatch`` messages. + The ``PartialResultSet`` that contains the last part has + ``complete_batch`` set to ``true``. """ batch_data: bytes = proto.Field( @@ -1479,9 +1482,30 @@ class ProtoRowsBatch(proto.Message): class PartialResultSet(proto.Message): - r"""A partial result set from the streaming query API. CBT client will - buffer partial_rows from result_sets until it gets a - resumption_token. + r"""A partial result set from the streaming query API. Cloud Bigtable + clients buffer partial results received in this message until a + ``resume_token`` is received. + + The pseudocode below describes how to buffer and parse a stream of + ``PartialResultSet`` messages. + + Having: + + - queue of row results waiting to be returned ``queue`` + - extensible buffer of bytes ``buffer`` + - a place to keep track of the most recent ``resume_token`` for + each PartialResultSet ``p`` received { if p.reset { ensure + ``queue`` is empty ensure ``buffer`` is empty } if + p.estimated_batch_size != 0 { (optional) ensure ``buffer`` is + sized to at least ``p.estimated_batch_size`` } if + ``p.proto_rows_batch`` is set { append + ``p.proto_rows_batch.bytes`` to ``buffer`` } if p.batch_checksum + is set and ``buffer`` is not empty { validate the checksum + matches the contents of ``buffer`` (see comments on + ``batch_checksum``) parse ``buffer`` as ``ProtoRows`` message, + clearing ``buffer`` add parsed rows to end of ``queue`` } if + p.resume_token is set { release results in ``queue`` save + ``p.resume_token`` in ``resume_token`` } } .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -1491,37 +1515,73 @@ class PartialResultSet(proto.Message): Partial rows in serialized ProtoRows format. This field is a member of `oneof`_ ``partial_rows``. - resume_token (bytes): - An opaque token sent by the server to allow query resumption - and signal the client to accumulate ``partial_rows`` since - the last non-empty ``resume_token``. On resumption, the - resumed query will return the remaining rows for this query. + batch_checksum (int): + CRC32C checksum of concatenated ``partial_rows`` data for + the current batch. + + When present, the buffered data from ``partial_rows`` forms + a complete parseable message of the appropriate type. - If there is a batch in progress, a non-empty - ``resume_token`` means that that the batch of - ``partial_rows`` will be complete after merging the - ``partial_rows`` from this response. The client must only - yield completed batches to the application, and must ensure - that any future retries send the latest token to avoid - returning duplicate data. + The client should mark the end of a parseable message and + prepare to receive a new one starting from the next + ``PartialResultSet`` message. Clients must verify the + checksum of the serialized batch before yielding it to the + caller. - The server may set 'resume_token' without a 'partial_rows'. - If there is a batch in progress the client should yield it. + This does NOT mean the values can be yielded to the callers + since a ``resume_token`` is required to safely do so. + + If ``resume_token`` is non-empty and any data has been + received since the last one, this field is guaranteed to be + non-empty. In other words, clients may assume that a batch + will never cross a ``resume_token`` boundary. + + This field is a member of `oneof`_ ``_batch_checksum``. + resume_token (bytes): + An opaque token sent by the server to allow query resumption + and signal that the buffered values constructed from + received ``partial_rows`` can be yielded to the caller. + Clients can provide this token in a subsequent request to + resume the result stream from the current point. + + When ``resume_token`` is non-empty, the buffered values + received from ``partial_rows`` since the last non-empty + ``resume_token`` can be yielded to the callers, provided + that the client keeps the value of ``resume_token`` and uses + it on subsequent retries. + + A ``resume_token`` may be sent without information in + ``partial_rows`` to checkpoint the progress of a sparse + query. Any previous ``partial_rows`` data should still be + yielded in this case, and the new ``resume_token`` should be + saved for future retries as normal. + + A ``resume_token`` will only be sent on a boundary where + there is either no ongoing result batch, or + ``batch_checksum`` is also populated. The server will also send a sentinel ``resume_token`` when last batch of ``partial_rows`` is sent. If the client retries the ExecuteQueryRequest with the sentinel ``resume_token``, the server will emit it again without any - ``partial_rows``, then return OK. + data in ``partial_rows``, then return OK. + reset (bool): + If ``true``, any data buffered since the last non-empty + ``resume_token`` must be discarded before the other parts of + this message, if any, are handled. estimated_batch_size (int): - Estimated size of a new batch. The server will always set - this when returning the first ``partial_rows`` of a batch, - and will not set it at any other time. - - The client can use this estimate to allocate an initial - buffer for the batched results. This helps minimize the - number of allocations required, though the buffer size may - still need to be increased if the estimate is too low. + Estimated size of the buffer required to hold the next batch + of results. + + This value will be sent with the first ``partial_rows`` of a + batch. That is, on the first ``partial_rows`` received in a + stream, on the first message after a ``batch_checksum`` + message, and any time ``reset`` is true. + + The client can use this estimate to allocate a buffer for + the next batch of results. This helps minimize the number of + allocations required, though the buffer size may still need + to be increased if the estimate is too low. """ proto_rows_batch: "ProtoRowsBatch" = proto.Field( @@ -1530,10 +1590,19 @@ class PartialResultSet(proto.Message): oneof="partial_rows", message="ProtoRowsBatch", ) + batch_checksum: int = proto.Field( + proto.UINT32, + number=6, + optional=True, + ) resume_token: bytes = proto.Field( proto.BYTES, number=5, ) + reset: bool = proto.Field( + proto.BOOL, + number=7, + ) estimated_batch_size: int = proto.Field( proto.INT32, number=4, diff --git a/scripts/fixup_bigtable_admin_v2_keywords.py b/scripts/fixup_bigtable_admin_v2_keywords.py index 0c242cb09..9e2dd2794 100644 --- a/scripts/fixup_bigtable_admin_v2_keywords.py +++ b/scripts/fixup_bigtable_admin_v2_keywords.py @@ -46,6 +46,8 @@ class bigtable_adminCallTransformer(cst.CSTTransformer): 'create_backup': ('parent', 'backup_id', 'backup', ), 'create_cluster': ('parent', 'cluster_id', 'cluster', ), 'create_instance': ('parent', 'instance_id', 'instance', 'clusters', ), + 'create_logical_view': ('parent', 'logical_view_id', 'logical_view', ), + 'create_materialized_view': ('parent', 'materialized_view_id', 'materialized_view', ), 'create_table': ('parent', 'table_id', 'table', 'initial_splits', ), 'create_table_from_snapshot': ('parent', 'table_id', 'source_snapshot', ), 'delete_app_profile': ('name', 'ignore_warnings', ), @@ -53,6 +55,8 @@ class bigtable_adminCallTransformer(cst.CSTTransformer): 'delete_backup': ('name', ), 'delete_cluster': ('name', ), 'delete_instance': ('name', ), + 'delete_logical_view': ('name', 'etag', ), + 'delete_materialized_view': ('name', 'etag', ), 'delete_snapshot': ('name', ), 'delete_table': ('name', ), 'drop_row_range': ('name', 'row_key_prefix', 'delete_all_data_from_table', ), @@ -63,6 +67,8 @@ class bigtable_adminCallTransformer(cst.CSTTransformer): 'get_cluster': ('name', ), 'get_iam_policy': ('resource', 'options', ), 'get_instance': ('name', ), + 'get_logical_view': ('name', ), + 'get_materialized_view': ('name', ), 'get_snapshot': ('name', ), 'get_table': ('name', 'view', ), 'list_app_profiles': ('parent', 'page_size', 'page_token', ), @@ -71,6 +77,8 @@ class bigtable_adminCallTransformer(cst.CSTTransformer): 'list_clusters': ('parent', 'page_token', ), 'list_hot_tablets': ('parent', 'start_time', 'end_time', 'page_size', 'page_token', ), 'list_instances': ('parent', 'page_token', ), + 'list_logical_views': ('parent', 'page_size', 'page_token', ), + 'list_materialized_views': ('parent', 'page_size', 'page_token', ), 'list_snapshots': ('parent', 'page_size', 'page_token', ), 'list_tables': ('parent', 'view', 'page_size', 'page_token', ), 'modify_column_families': ('name', 'modifications', 'ignore_warnings', ), @@ -85,8 +93,10 @@ class bigtable_adminCallTransformer(cst.CSTTransformer): 'update_authorized_view': ('authorized_view', 'update_mask', 'ignore_warnings', ), 'update_backup': ('backup', 'update_mask', ), 'update_cluster': ('name', 'location', 'state', 'serve_nodes', 'node_scaling_factor', 'cluster_config', 'default_storage_type', 'encryption_config', ), - 'update_instance': ('display_name', 'name', 'state', 'type_', 'labels', 'create_time', 'satisfies_pzs', ), - 'update_table': ('table', 'update_mask', ), + 'update_instance': ('display_name', 'name', 'state', 'type_', 'labels', 'create_time', 'satisfies_pzs', 'satisfies_pzi', ), + 'update_logical_view': ('logical_view', 'update_mask', ), + 'update_materialized_view': ('materialized_view', 'update_mask', ), + 'update_table': ('table', 'update_mask', 'ignore_warnings', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/scripts/fixup_bigtable_v2_keywords.py b/scripts/fixup_bigtable_v2_keywords.py index 218a54902..466b1d1c7 100644 --- a/scripts/fixup_bigtable_v2_keywords.py +++ b/scripts/fixup_bigtable_v2_keywords.py @@ -40,15 +40,16 @@ class bigtableCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'check_and_mutate_row': ('row_key', 'table_name', 'authorized_view_name', 'app_profile_id', 'predicate_filter', 'true_mutations', 'false_mutations', ), - 'execute_query': ('instance_name', 'query', 'params', 'app_profile_id', 'proto_format', 'resume_token', ), + 'execute_query': ('instance_name', 'query', 'params', 'app_profile_id', 'prepared_query', 'proto_format', 'resume_token', ), 'generate_initial_change_stream_partitions': ('table_name', 'app_profile_id', ), 'mutate_row': ('row_key', 'mutations', 'table_name', 'authorized_view_name', 'app_profile_id', ), 'mutate_rows': ('entries', 'table_name', 'authorized_view_name', 'app_profile_id', ), 'ping_and_warm': ('name', 'app_profile_id', ), + 'prepare_query': ('instance_name', 'query', 'param_types', 'app_profile_id', 'proto_format', ), 'read_change_stream': ('table_name', 'app_profile_id', 'partition', 'start_time', 'continuation_tokens', 'end_time', 'heartbeat_duration', ), 'read_modify_write_row': ('row_key', 'rules', 'table_name', 'authorized_view_name', 'app_profile_id', ), - 'read_rows': ('table_name', 'authorized_view_name', 'app_profile_id', 'rows', 'filter', 'rows_limit', 'request_stats_view', 'reversed', ), - 'sample_row_keys': ('table_name', 'authorized_view_name', 'app_profile_id', ), + 'read_rows': ('table_name', 'authorized_view_name', 'materialized_view_name', 'app_profile_id', 'rows', 'filter', 'rows_limit', 'request_stats_view', 'reversed', ), + 'sample_row_keys': ('table_name', 'authorized_view_name', 'materialized_view_name', 'app_profile_id', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/tests/unit/data/_async/test_client.py b/tests/unit/data/_async/test_client.py index 18ff69ffd..d59a86187 100644 --- a/tests/unit/data/_async/test_client.py +++ b/tests/unit/data/_async/test_client.py @@ -377,7 +377,17 @@ async def test__manage_channel_ping_and_warm(self): import time import threading + if CrossSync.is_async: + from google.cloud.bigtable_v2.services.bigtable.transports.grpc_asyncio import ( + _LoggingClientAIOInterceptor as Interceptor, + ) + else: + from google.cloud.bigtable_v2.services.bigtable.transports.grpc import ( + _LoggingClientInterceptor as Interceptor, + ) + client_mock = mock.Mock() + client_mock.transport._interceptor = Interceptor() client_mock._is_closed.is_set.return_value = False client_mock._channel_init_time = time.monotonic() orig_channel = client_mock.transport.grpc_channel diff --git a/tests/unit/data/_sync_autogen/test_client.py b/tests/unit/data/_sync_autogen/test_client.py index c5c6bac30..c77381280 100644 --- a/tests/unit/data/_sync_autogen/test_client.py +++ b/tests/unit/data/_sync_autogen/test_client.py @@ -289,8 +289,12 @@ def test__manage_channel_ping_and_warm(self): """_manage channel should call ping and warm internally""" import time import threading + from google.cloud.bigtable_v2.services.bigtable.transports.grpc import ( + _LoggingClientInterceptor as Interceptor, + ) client_mock = mock.Mock() + client_mock.transport._interceptor = Interceptor() client_mock._is_closed.is_set.return_value = False client_mock._channel_init_time = time.monotonic() orig_channel = client_mock.transport.grpc_channel diff --git a/tests/unit/gapic/bigtable_admin_v2/test_bigtable_instance_admin.py b/tests/unit/gapic/bigtable_admin_v2/test_bigtable_instance_admin.py index 3f79e11a4..eeb014f54 100644 --- a/tests/unit/gapic/bigtable_admin_v2/test_bigtable_instance_admin.py +++ b/tests/unit/gapic/bigtable_admin_v2/test_bigtable_instance_admin.py @@ -80,6 +80,14 @@ import google.auth +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + async def mock_async_gen(data, chunk_size=1): for i in range(0, len(data)): # pragma: NO COVER chunk = data[i : i + chunk_size] @@ -354,6 +362,49 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = BigtableInstanceAdminClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = BigtableInstanceAdminClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + @pytest.mark.parametrize( "client_class,transport_name", [ @@ -1535,6 +1586,7 @@ def test_get_instance(request_type, transport: str = "grpc"): state=instance.Instance.State.READY, type_=instance.Instance.Type.PRODUCTION, satisfies_pzs=True, + satisfies_pzi=True, ) response = client.get_instance(request) @@ -1551,6 +1603,7 @@ def test_get_instance(request_type, transport: str = "grpc"): assert response.state == instance.Instance.State.READY assert response.type_ == instance.Instance.Type.PRODUCTION assert response.satisfies_pzs is True + assert response.satisfies_pzi is True def test_get_instance_non_empty_request_with_auto_populated_field(): @@ -1682,6 +1735,7 @@ async def test_get_instance_async( state=instance.Instance.State.READY, type_=instance.Instance.Type.PRODUCTION, satisfies_pzs=True, + satisfies_pzi=True, ) ) response = await client.get_instance(request) @@ -1699,6 +1753,7 @@ async def test_get_instance_async( assert response.state == instance.Instance.State.READY assert response.type_ == instance.Instance.Type.PRODUCTION assert response.satisfies_pzs is True + assert response.satisfies_pzi is True @pytest.mark.asyncio @@ -2202,6 +2257,7 @@ def test_update_instance(request_type, transport: str = "grpc"): state=instance.Instance.State.READY, type_=instance.Instance.Type.PRODUCTION, satisfies_pzs=True, + satisfies_pzi=True, ) response = client.update_instance(request) @@ -2218,6 +2274,7 @@ def test_update_instance(request_type, transport: str = "grpc"): assert response.state == instance.Instance.State.READY assert response.type_ == instance.Instance.Type.PRODUCTION assert response.satisfies_pzs is True + assert response.satisfies_pzi is True def test_update_instance_non_empty_request_with_auto_populated_field(): @@ -2350,6 +2407,7 @@ async def test_update_instance_async( state=instance.Instance.State.READY, type_=instance.Instance.Type.PRODUCTION, satisfies_pzs=True, + satisfies_pzi=True, ) ) response = await client.update_instance(request) @@ -2367,6 +2425,7 @@ async def test_update_instance_async( assert response.state == instance.Instance.State.READY assert response.type_ == instance.Instance.Type.PRODUCTION assert response.satisfies_pzs is True + assert response.satisfies_pzi is True @pytest.mark.asyncio @@ -6896,6 +6955,7 @@ def test_delete_app_profile_flattened(): # using the keyword arguments to the method. client.delete_app_profile( name="name_value", + ignore_warnings=True, ) # Establish that the underlying call was made with the expected @@ -6905,6 +6965,9 @@ def test_delete_app_profile_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].ignore_warnings + mock_val = True + assert arg == mock_val def test_delete_app_profile_flattened_error(): @@ -6918,6 +6981,7 @@ def test_delete_app_profile_flattened_error(): client.delete_app_profile( bigtable_instance_admin.DeleteAppProfileRequest(), name="name_value", + ignore_warnings=True, ) @@ -6939,6 +7003,7 @@ async def test_delete_app_profile_flattened_async(): # using the keyword arguments to the method. response = await client.delete_app_profile( name="name_value", + ignore_warnings=True, ) # Establish that the underlying call was made with the expected @@ -6948,6 +7013,9 @@ async def test_delete_app_profile_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].ignore_warnings + mock_val = True + assert arg == mock_val @pytest.mark.asyncio @@ -6962,6 +7030,7 @@ async def test_delete_app_profile_flattened_error_async(): await client.delete_app_profile( bigtable_instance_admin.DeleteAppProfileRequest(), name="name_value", + ignore_warnings=True, ) @@ -8539,13 +8608,80 @@ async def test_list_hot_tablets_async_pages(): assert page_.raw_page.next_page_token == token -def test_create_instance_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.CreateLogicalViewRequest, + dict, + ], +) +def test_create_logical_view(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.CreateLogicalViewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_logical_view_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.CreateLogicalViewRequest( + parent="parent_value", + logical_view_id="logical_view_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_logical_view(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable_instance_admin.CreateLogicalViewRequest( + parent="parent_value", + logical_view_id="logical_view_id_value", + ) + + +def test_create_logical_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -8553,193 +8689,368 @@ def test_create_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_instance in client._transport._wrapped_methods + assert ( + client._transport.create_logical_view in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.create_logical_view + ] = mock_rpc request = {} - client.create_instance(request) + client.create_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_instance(request) + client.create_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_instance_rest_required_fields( - request_type=bigtable_instance_admin.CreateInstanceRequest, +@pytest.mark.asyncio +async def test_create_logical_view_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BigtableInstanceAdminRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["instance_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.create_logical_view + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_logical_view + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.create_logical_view(request) - jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" + await client.create_logical_view(request) - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_create_logical_view_async( + transport: str = "grpc_asyncio", + request_type=bigtable_instance_admin.CreateLogicalViewRequest, +): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.create_instance(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_logical_view(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.CreateLogicalViewRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_create_instance_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.create_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "instanceId", - "instance", - "clusters", - ) - ) - ) +@pytest.mark.asyncio +async def test_create_logical_view_async_from_dict(): + await test_create_logical_view_async(request_type=dict) -def test_create_instance_rest_flattened(): +def test_create_logical_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.CreateLogicalViewRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - instance_id="instance_id_value", - instance=gba_instance.Instance(name="name_value"), - clusters={"key_value": gba_instance.Cluster(name="name_value")}, - ) - mock_args.update(sample_request) + request.parent = "parent_value" - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_logical_view(request) - client.create_instance(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*}/instances" % client.transport._host, args[1] + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_logical_view_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.CreateLogicalViewRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) + await client.create_logical_view(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_create_instance_rest_flattened_error(transport: str = "rest"): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_logical_view_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_logical_view), "__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_logical_view( + parent="parent_value", + logical_view=instance.LogicalView(name="name_value"), + logical_view_id="logical_view_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].logical_view + mock_val = instance.LogicalView(name="name_value") + assert arg == mock_val + arg = args[0].logical_view_id + mock_val = "logical_view_id_value" + assert arg == mock_val + + +def test_create_logical_view_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_instance( - bigtable_instance_admin.CreateInstanceRequest(), + client.create_logical_view( + bigtable_instance_admin.CreateLogicalViewRequest(), parent="parent_value", - instance_id="instance_id_value", - instance=gba_instance.Instance(name="name_value"), - clusters={"key_value": gba_instance.Cluster(name="name_value")}, + logical_view=instance.LogicalView(name="name_value"), + logical_view_id="logical_view_id_value", ) -def test_get_instance_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_create_logical_view_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_logical_view( + parent="parent_value", + logical_view=instance.LogicalView(name="name_value"), + logical_view_id="logical_view_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].logical_view + mock_val = instance.LogicalView(name="name_value") + assert arg == mock_val + arg = args[0].logical_view_id + mock_val = "logical_view_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_logical_view_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_logical_view( + bigtable_instance_admin.CreateLogicalViewRequest(), + parent="parent_value", + logical_view=instance.LogicalView(name="name_value"), + logical_view_id="logical_view_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.GetLogicalViewRequest, + dict, + ], +) +def test_get_logical_view(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = instance.LogicalView( + name="name_value", + query="query_value", + etag="etag_value", + ) + response = client.get_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.GetLogicalViewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.LogicalView) + assert response.name == "name_value" + assert response.query == "query_value" + assert response.etag == "etag_value" + + +def test_get_logical_view_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.GetLogicalViewRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_logical_view(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable_instance_admin.GetLogicalViewRequest( + name="name_value", + ) + + +def test_get_logical_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -8747,173 +9058,335 @@ def test_get_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_instance in client._transport._wrapped_methods + assert client._transport.get_logical_view in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.get_logical_view + ] = mock_rpc request = {} - client.get_instance(request) + client.get_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_instance(request) + client.get_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_instance_rest_required_fields( - request_type=bigtable_instance_admin.GetInstanceRequest, +@pytest.mark.asyncio +async def test_get_logical_view_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BigtableInstanceAdminRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.get_logical_view + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_logical_view + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.get_logical_view(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + await client.get_logical_view(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = instance.Instance() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result +@pytest.mark.asyncio +async def test_get_logical_view_async( + transport: str = "grpc_asyncio", + request_type=bigtable_instance_admin.GetLogicalViewRequest, +): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value = Response() - response_value.status_code = 200 + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.LogicalView( + name="name_value", + query="query_value", + etag="etag_value", + ) + ) + response = await client.get_logical_view(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.GetLogicalViewRequest() + assert args[0] == request - response = client.get_instance(request) + # Establish that the response is the type that we expect. + assert isinstance(response, instance.LogicalView) + assert response.name == "name_value" + assert response.query == "query_value" + assert response.etag == "etag_value" - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_get_logical_view_async_from_dict(): + await test_get_logical_view_async(request_type=dict) -def test_get_instance_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials + +def test_get_logical_view_field_headers(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.get_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.GetLogicalViewRequest() + + request.name = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + call.return_value = instance.LogicalView() + client.get_logical_view(request) -def test_get_instance_rest_flattened(): + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_logical_view_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.GetLogicalViewRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.LogicalView() + ) + await client.get_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_logical_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = instance.Instance() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = instance.LogicalView() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_logical_view( + name="name_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/instances/sample2"} + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( + +def test_get_logical_view_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=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_logical_view( + bigtable_instance_admin.GetLogicalViewRequest(), name="name_value", ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.get_instance(**mock_args) +@pytest.mark.asyncio +async def test_get_logical_view_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = instance.LogicalView() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.LogicalView() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_logical_view( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{name=projects/*/instances/*}" % client.transport._host, args[1] - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_get_instance_rest_flattened_error(transport: str = "rest"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_get_logical_view_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_instance( - bigtable_instance_admin.GetInstanceRequest(), + await client.get_logical_view( + bigtable_instance_admin.GetLogicalViewRequest(), name="name_value", ) -def test_list_instances_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.ListLogicalViewsRequest, + dict, + ], +) +def test_list_logical_views(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable_instance_admin.ListLogicalViewsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_logical_views(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.ListLogicalViewsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLogicalViewsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_logical_views_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.ListLogicalViewsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_logical_views(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable_instance_admin.ListLogicalViewsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_logical_views_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -8921,295 +9394,536 @@ def test_list_instances_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_instances in client._transport._wrapped_methods + assert ( + client._transport.list_logical_views in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.list_logical_views + ] = mock_rpc request = {} - client.list_instances(request) + client.list_logical_views(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_instances(request) + client.list_logical_views(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_instances_rest_required_fields( - request_type=bigtable_instance_admin.ListInstancesRequest, +@pytest.mark.asyncio +async def test_list_logical_views_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BigtableInstanceAdminRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.list_logical_views + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_instances._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_logical_views + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_logical_views(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_instances._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_token",)) - jsonified_request.update(unset_fields) + await client.list_logical_views(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListInstancesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result +@pytest.mark.asyncio +async def test_list_logical_views_async( + transport: str = "grpc_asyncio", + request_type=bigtable_instance_admin.ListLogicalViewsRequest, +): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value = Response() - response_value.status_code = 200 + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListInstancesResponse.pb( - return_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListLogicalViewsResponse( + next_page_token="next_page_token_value", ) - json_return_value = json_format.MessageToJson(return_value) + ) + response = await client.list_logical_views(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.ListLogicalViewsRequest() + assert args[0] == request - response = client.list_instances(request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLogicalViewsAsyncPager) + assert response.next_page_token == "next_page_token_value" - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_list_logical_views_async_from_dict(): + await test_list_logical_views_async(request_type=dict) -def test_list_instances_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials + +def test_list_logical_views_field_headers(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.list_instances._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageToken",)) & set(("parent",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.ListLogicalViewsRequest() + request.parent = "parent_value" -def test_list_instances_rest_flattened(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + call.return_value = bigtable_instance_admin.ListLogicalViewsResponse() + client.list_logical_views(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_logical_views_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListInstancesResponse() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.ListLogicalViewsRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListLogicalViewsResponse() ) - mock_args.update(sample_request) + await client.list_logical_views(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.list_instances(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_logical_views_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable_instance_admin.ListLogicalViewsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_logical_views( + parent="parent_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*}/instances" % client.transport._host, args[1] - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_list_instances_rest_flattened_error(transport: str = "rest"): +def test_list_logical_views_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_instances( - bigtable_instance_admin.ListInstancesRequest(), + client.list_logical_views( + bigtable_instance_admin.ListLogicalViewsRequest(), parent="parent_value", ) -def test_update_instance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_list_logical_views_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.update_instance in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable_instance_admin.ListLogicalViewsResponse() - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListLogicalViewsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_logical_views( + parent="parent_value", ) - client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc - - request = {} - client.update_instance(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - client.update_instance(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_list_logical_views_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_logical_views( + bigtable_instance_admin.ListLogicalViewsRequest(), + parent="parent_value", + ) -def test_update_instance_rest_required_fields(request_type=instance.Instance): - transport_class = transports.BigtableInstanceAdminRestTransport - request_init = {} - request_init["display_name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +def test_list_logical_views_pager(transport_name: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + instance.LogicalView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + ], + ), + RuntimeError, + ) - jsonified_request["displayName"] = "display_name_value" + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_logical_views(request={}, retry=retry, timeout=timeout) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - # verify required fields with non-default values are left alone - assert "displayName" in jsonified_request - assert jsonified_request["displayName"] == "display_name_value" + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.LogicalView) for i in results) + +def test_list_logical_views_pages(transport_name: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = instance.Instance() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "put", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + instance.LogicalView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + ], + ), + RuntimeError, + ) + pages = list(client.list_logical_views(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_list_logical_views_async_pager(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + instance.LogicalView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_logical_views( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - response = client.update_instance(request) + assert len(responses) == 6 + assert all(isinstance(i, instance.LogicalView) for i in responses) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_list_logical_views_async_pages(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_update_instance_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + instance.LogicalView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_logical_views(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.UpdateLogicalViewRequest, + dict, + ], +) +def test_update_logical_view(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - unset_fields = transport.update_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("displayName",))) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_logical_view(request) -def test_partial_update_instance_rest_use_cached_wrapped_rpc(): + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.UpdateLogicalViewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_logical_view_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.UpdateLogicalViewRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_logical_view), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_logical_view(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable_instance_admin.UpdateLogicalViewRequest() + + +def test_update_logical_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -9218,8 +9932,7 @@ def test_partial_update_instance_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.partial_update_instance - in client._transport._wrapped_methods + client._transport.update_logical_view in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -9228,344 +9941,347 @@ def test_partial_update_instance_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.partial_update_instance + client._transport.update_logical_view ] = mock_rpc - request = {} - client.partial_update_instance(request) + client.update_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.partial_update_instance(request) + client.update_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_partial_update_instance_rest_required_fields( - request_type=bigtable_instance_admin.PartialUpdateInstanceRequest, +@pytest.mark.asyncio +async def test_update_logical_view_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BigtableInstanceAdminRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.update_logical_view + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).partial_update_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_logical_view + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.update_logical_view(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).partial_update_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_logical_view(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_logical_view_async( + transport: str = "grpc_asyncio", + request_type=bigtable_instance_admin.UpdateLogicalViewRequest, +): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.UpdateLogicalViewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_logical_view_async_from_dict(): + await test_update_logical_view_async(request_type=dict) + +def test_update_logical_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.UpdateLogicalViewRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.logical_view.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_logical_view), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_logical_view(request) - response = client.partial_update_instance(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "logical_view.name=name_value", + ) in kw["metadata"] -def test_partial_update_instance_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_update_logical_view_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.partial_update_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "instance", - "updateMask", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.UpdateLogicalViewRequest() + + request.logical_view.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_logical_view), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - ) + await client.update_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "logical_view.name=name_value", + ) in kw["metadata"] -def test_partial_update_instance_rest_flattened(): + +def test_update_logical_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"instance": {"name": "projects/sample1/instances/sample2"}} - - # get truthy value for each flattened field - mock_args = dict( - instance=gba_instance.Instance(name="name_value"), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_logical_view), "__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_logical_view( + logical_view=instance.LogicalView(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.partial_update_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{instance.name=projects/*/instances/*}" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].logical_view + mock_val = instance.LogicalView(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val -def test_partial_update_instance_rest_flattened_error(transport: str = "rest"): +def test_update_logical_view_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.partial_update_instance( - bigtable_instance_admin.PartialUpdateInstanceRequest(), - instance=gba_instance.Instance(name="name_value"), + client.update_logical_view( + bigtable_instance_admin.UpdateLogicalViewRequest(), + logical_view=instance.LogicalView(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_instance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_update_logical_view_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.delete_instance in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_logical_view( + logical_view=instance.LogicalView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc - - request = {} - client.delete_instance(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].logical_view + mock_val = instance.LogicalView(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val - client.delete_instance(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_update_logical_view_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_logical_view( + bigtable_instance_admin.UpdateLogicalViewRequest(), + logical_view=instance.LogicalView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -def test_delete_instance_rest_required_fields( - request_type=bigtable_instance_admin.DeleteInstanceRequest, -): - transport_class = transports.BigtableInstanceAdminRestTransport - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.DeleteLogicalViewRequest, + dict, + ], +) +def test_delete_logical_view(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_logical_view(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.DeleteLogicalViewRequest() + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the response is the type that we expect. + assert response is None - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_delete_logical_view_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.delete_instance(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_delete_instance_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials + transport="grpc", ) - unset_fields = transport.delete_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -def test_delete_instance_rest_flattened(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.DeleteLogicalViewRequest( + name="name_value", + etag="etag_value", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/instances/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.delete_instance(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{name=projects/*/instances/*}" % client.transport._host, args[1] + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_logical_view), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - -def test_delete_instance_rest_flattened_error(transport: str = "rest"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_instance( - bigtable_instance_admin.DeleteInstanceRequest(), + client.delete_logical_view(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable_instance_admin.DeleteLogicalViewRequest( name="name_value", + etag="etag_value", ) -def test_create_cluster_rest_use_cached_wrapped_rpc(): +def test_delete_logical_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -9573,202 +10289,331 @@ def test_create_cluster_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_cluster in client._transport._wrapped_methods + assert ( + client._transport.delete_logical_view in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.delete_logical_view + ] = mock_rpc request = {} - client.create_cluster(request) + client.delete_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + client.delete_logical_view(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_logical_view_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 wrapper_fn.reset_mock() - client.create_cluster(request) + # Ensure method has been cached + assert ( + client._client._transport.delete_logical_view + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_logical_view + ] = mock_rpc + + request = {} + await client.delete_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_cluster_rest_required_fields( - request_type=bigtable_instance_admin.CreateClusterRequest, +@pytest.mark.asyncio +async def test_delete_logical_view_async( + transport: str = "grpc_asyncio", + request_type=bigtable_instance_admin.DeleteLogicalViewRequest, ): - transport_class = transports.BigtableInstanceAdminRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["cluster_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped - assert "clusterId" not in jsonified_request + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_logical_view(request) - # verify required fields with default values are now present - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == request_init["cluster_id"] + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.DeleteLogicalViewRequest() + assert args[0] == request - jsonified_request["parent"] = "parent_value" - jsonified_request["clusterId"] = "cluster_id_value" + # Establish that the response is the type that we expect. + assert response is None - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("cluster_id",)) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == "cluster_id_value" +@pytest.mark.asyncio +async def test_delete_logical_view_async_from_dict(): + await test_delete_logical_view_async(request_type=dict) + +def test_delete_logical_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.DeleteLogicalViewRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_logical_view), "__call__" + ) as call: + call.return_value = None + client.delete_logical_view(request) - response = client.create_cluster(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [ - ( - "clusterId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_create_cluster_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_delete_logical_view_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.create_cluster._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("clusterId",)) - & set( - ( - "parent", - "clusterId", - "cluster", - ) - ) - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.DeleteLogicalViewRequest() + request.name = "name_value" -def test_create_cluster_rest_flattened(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_logical_view), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_logical_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_logical_view), "__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_logical_view( + name="name_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/instances/sample2"} + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - cluster_id="cluster_id_value", - cluster=instance.Cluster(name="name_value"), + +def test_delete_logical_view_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_logical_view( + bigtable_instance_admin.DeleteLogicalViewRequest(), + name="name_value", ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.create_cluster(**mock_args) +@pytest.mark.asyncio +async def test_delete_logical_view_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_logical_view( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*/instances/*}/clusters" % client.transport._host, - args[1], + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_logical_view_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_logical_view( + bigtable_instance_admin.DeleteLogicalViewRequest(), + name="name_value", ) -def test_create_cluster_rest_flattened_error(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.CreateMaterializedViewRequest, + dict, + ], +) +def test_create_materialized_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_cluster( - bigtable_instance_admin.CreateClusterRequest(), + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_materialized_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.CreateMaterializedViewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_materialized_view_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.CreateMaterializedViewRequest( + parent="parent_value", + materialized_view_id="materialized_view_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_materialized_view(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable_instance_admin.CreateMaterializedViewRequest( parent="parent_value", - cluster_id="cluster_id_value", - cluster=instance.Cluster(name="name_value"), + materialized_view_id="materialized_view_id_value", ) -def test_get_cluster_rest_use_cached_wrapped_rpc(): +def test_create_materialized_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -9776,351 +10621,375 @@ def test_get_cluster_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_cluster in client._transport._wrapped_methods + assert ( + client._transport.create_materialized_view + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_cluster] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.create_materialized_view + ] = mock_rpc request = {} - client.get_cluster(request) + client.create_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_cluster(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_cluster_rest_required_fields( - request_type=bigtable_instance_admin.GetClusterRequest, +@pytest.mark.asyncio +async def test_create_materialized_view_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BigtableInstanceAdminRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.create_materialized_view + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_materialized_view + ] = mock_rpc - jsonified_request["name"] = "name_value" + request = {} + await client.create_materialized_view(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.create_materialized_view(request) - # Designate an appropriate value for the returned response. - return_value = instance.Cluster() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_create_materialized_view_async( + transport: str = "grpc_asyncio", + request_type=bigtable_instance_admin.CreateMaterializedViewRequest, +): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.get_cluster(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_materialized_view(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.CreateMaterializedViewRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_get_cluster_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.get_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) +@pytest.mark.asyncio +async def test_create_materialized_view_async_from_dict(): + await test_create_materialized_view_async(request_type=dict) -def test_get_cluster_rest_flattened(): +def test_create_materialized_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = instance.Cluster() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.CreateMaterializedViewRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_materialized_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_materialized_view_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.CreateMaterializedViewRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.create_materialized_view(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.get_cluster(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_materialized_view_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__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_materialized_view( + parent="parent_value", + materialized_view=instance.MaterializedView(name="name_value"), + materialized_view_id="materialized_view_id_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{name=projects/*/instances/*/clusters/*}" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].materialized_view + mock_val = instance.MaterializedView(name="name_value") + assert arg == mock_val + arg = args[0].materialized_view_id + mock_val = "materialized_view_id_value" + assert arg == mock_val -def test_get_cluster_rest_flattened_error(transport: str = "rest"): +def test_create_materialized_view_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_cluster( - bigtable_instance_admin.GetClusterRequest(), - name="name_value", + client.create_materialized_view( + bigtable_instance_admin.CreateMaterializedViewRequest(), + parent="parent_value", + materialized_view=instance.MaterializedView(name="name_value"), + materialized_view_id="materialized_view_id_value", ) -def test_list_clusters_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_create_materialized_view_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.list_clusters in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_materialized_view( + parent="parent_value", + materialized_view=instance.MaterializedView(name="name_value"), + materialized_view_id="materialized_view_id_value", ) - client._transport._wrapped_methods[client._transport.list_clusters] = mock_rpc - - request = {} - client.list_clusters(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].materialized_view + mock_val = instance.MaterializedView(name="name_value") + assert arg == mock_val + arg = args[0].materialized_view_id + mock_val = "materialized_view_id_value" + assert arg == mock_val - client.list_clusters(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_create_materialized_view_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_materialized_view( + bigtable_instance_admin.CreateMaterializedViewRequest(), + parent="parent_value", + materialized_view=instance.MaterializedView(name="name_value"), + materialized_view_id="materialized_view_id_value", + ) -def test_list_clusters_rest_required_fields( - request_type=bigtable_instance_admin.ListClustersRequest, -): - transport_class = transports.BigtableInstanceAdminRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_clusters._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_clusters._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_token",)) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.GetMaterializedViewRequest, + dict, + ], +) +def test_get_materialized_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListClustersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_clusters(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = instance.MaterializedView( + name="name_value", + query="query_value", + etag="etag_value", + deletion_protection=True, + ) + response = client.get_materialized_view(request) -def test_list_clusters_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.GetMaterializedViewRequest() + assert args[0] == request - unset_fields = transport.list_clusters._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageToken",)) & set(("parent",))) + # Establish that the response is the type that we expect. + assert isinstance(response, instance.MaterializedView) + assert response.name == "name_value" + assert response.query == "query_value" + assert response.etag == "etag_value" + assert response.deletion_protection is True -def test_list_clusters_rest_flattened(): +def test_get_materialized_view_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListClustersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/instances/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.list_clusters(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*/instances/*}/clusters" % client.transport._host, - args[1], - ) - - -def test_list_clusters_rest_flattened_error(transport: str = "rest"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.GetMaterializedViewRequest( + name="name_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_clusters( - bigtable_instance_admin.ListClustersRequest(), - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_materialized_view(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable_instance_admin.GetMaterializedViewRequest( + name="name_value", ) -def test_update_cluster_rest_use_cached_wrapped_rpc(): +def test_get_materialized_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -10128,39 +10997,42 @@ def test_update_cluster_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_cluster in client._transport._wrapped_methods + assert ( + client._transport.get_materialized_view + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_cluster] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.get_materialized_view + ] = mock_rpc request = {} - client.update_cluster(request) + client.get_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_cluster(request) + client.get_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_partial_update_cluster_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_get_materialized_view_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) # Should wrap all calls on client creation @@ -10169,188 +11041,306 @@ def test_partial_update_cluster_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.partial_update_cluster - in client._transport._wrapped_methods + client._client._transport.get_materialized_view + in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.partial_update_cluster + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_materialized_view ] = mock_rpc request = {} - client.partial_update_cluster(request) + await client.get_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.partial_update_cluster(request) + await client.get_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_partial_update_cluster_rest_required_fields( - request_type=bigtable_instance_admin.PartialUpdateClusterRequest, +@pytest.mark.asyncio +async def test_get_materialized_view_async( + transport: str = "grpc_asyncio", + request_type=bigtable_instance_admin.GetMaterializedViewRequest, ): - transport_class = transports.BigtableInstanceAdminRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).partial_update_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.MaterializedView( + name="name_value", + query="query_value", + etag="etag_value", + deletion_protection=True, + ) + ) + response = await client.get_materialized_view(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.GetMaterializedViewRequest() + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).partial_update_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) - jsonified_request.update(unset_fields) + # Establish that the response is the type that we expect. + assert isinstance(response, instance.MaterializedView) + assert response.name == "name_value" + assert response.query == "query_value" + assert response.etag == "etag_value" + assert response.deletion_protection is True + + +@pytest.mark.asyncio +async def test_get_materialized_view_async_from_dict(): + await test_get_materialized_view_async(request_type=dict) - # verify required fields with non-default values are left alone +def test_get_materialized_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.GetMaterializedViewRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + call.return_value = instance.MaterializedView() + client.get_materialized_view(request) - response = client.partial_update_cluster(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_partial_update_cluster_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_get_materialized_view_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.partial_update_cluster._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "cluster", - "updateMask", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.GetMaterializedViewRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.MaterializedView() ) - ) + await client.get_materialized_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_partial_update_cluster_rest_flattened(): +def test_get_materialized_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = instance.MaterializedView() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_materialized_view( + name="name_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} - } + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( - cluster=instance.Cluster(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + +def test_get_materialized_view_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=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_materialized_view( + bigtable_instance_admin.GetMaterializedViewRequest(), + name="name_value", ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.partial_update_cluster(**mock_args) +@pytest.mark.asyncio +async def test_get_materialized_view_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = instance.MaterializedView() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.MaterializedView() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_materialized_view( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{cluster.name=projects/*/instances/*/clusters/*}" - % client.transport._host, - args[1], + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_materialized_view_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_materialized_view( + bigtable_instance_admin.GetMaterializedViewRequest(), + name="name_value", ) -def test_partial_update_cluster_rest_flattened_error(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.ListMaterializedViewsRequest, + dict, + ], +) +def test_list_materialized_views(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.partial_update_cluster( - bigtable_instance_admin.PartialUpdateClusterRequest(), - cluster=instance.Cluster(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse( + next_page_token="next_page_token_value", ) + response = client.list_materialized_views(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.ListMaterializedViewsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMaterializedViewsPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_cluster_rest_use_cached_wrapped_rpc(): +def test_list_materialized_views_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.ListMaterializedViewsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_materialized_views(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable_instance_admin.ListMaterializedViewsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_materialized_views_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -10358,388 +11348,537 @@ def test_delete_cluster_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_cluster in client._transport._wrapped_methods + assert ( + client._transport.list_materialized_views + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_cluster] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.list_materialized_views + ] = mock_rpc request = {} - client.delete_cluster(request) + client.list_materialized_views(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_cluster(request) + client.list_materialized_views(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_cluster_rest_required_fields( - request_type=bigtable_instance_admin.DeleteClusterRequest, +@pytest.mark.asyncio +async def test_list_materialized_views_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BigtableInstanceAdminRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.list_materialized_views + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_materialized_views + ] = mock_rpc - jsonified_request["name"] = "name_value" + request = {} + await client.list_materialized_views(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + await client.list_materialized_views(request) - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, - } - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 - json_return_value = "" +@pytest.mark.asyncio +async def test_list_materialized_views_async( + transport: str = "grpc_asyncio", + request_type=bigtable_instance_admin.ListMaterializedViewsRequest, +): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.delete_cluster(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListMaterializedViewsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_materialized_views(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.ListMaterializedViewsRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMaterializedViewsAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_cluster_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.delete_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) +@pytest.mark.asyncio +async def test_list_materialized_views_async_from_dict(): + await test_list_materialized_views_async(request_type=dict) -def test_delete_cluster_rest_flattened(): +def test_list_materialized_views_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = None + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.ListMaterializedViewsRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() + client.list_materialized_views(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_materialized_views_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.ListMaterializedViewsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListMaterializedViewsResponse() ) - mock_args.update(sample_request) + await client.list_materialized_views(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.delete_cluster(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_materialized_views_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_materialized_views( + parent="parent_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{name=projects/*/instances/*/clusters/*}" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_delete_cluster_rest_flattened_error(transport: str = "rest"): +def test_list_materialized_views_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_cluster( - bigtable_instance_admin.DeleteClusterRequest(), - name="name_value", + client.list_materialized_views( + bigtable_instance_admin.ListMaterializedViewsRequest(), + parent="parent_value", ) -def test_create_app_profile_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_list_materialized_views_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() - # Ensure method has been cached - assert ( - client._transport.create_app_profile in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListMaterializedViewsResponse() ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_materialized_views( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.create_app_profile - ] = mock_rpc - request = {} - client.create_app_profile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - client.create_app_profile(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_list_materialized_views_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_materialized_views( + bigtable_instance_admin.ListMaterializedViewsRequest(), + parent="parent_value", + ) -def test_create_app_profile_rest_required_fields( - request_type=bigtable_instance_admin.CreateAppProfileRequest, -): - transport_class = transports.BigtableInstanceAdminRestTransport - request_init = {} - request_init["parent"] = "" - request_init["app_profile_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +def test_list_materialized_views_pager(transport_name: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # verify fields with default values are dropped - assert "appProfileId" not in jsonified_request - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_app_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + instance.MaterializedView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + ], + ), + RuntimeError, + ) - # verify required fields with default values are now present - assert "appProfileId" in jsonified_request - assert jsonified_request["appProfileId"] == request_init["app_profile_id"] + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_materialized_views(request={}, retry=retry, timeout=timeout) - jsonified_request["parent"] = "parent_value" - jsonified_request["appProfileId"] = "app_profile_id_value" + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_app_profile._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "app_profile_id", - "ignore_warnings", - ) - ) - jsonified_request.update(unset_fields) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.MaterializedView) for i in results) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "appProfileId" in jsonified_request - assert jsonified_request["appProfileId"] == "app_profile_id_value" +def test_list_materialized_views_pages(transport_name: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = instance.AppProfile() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + instance.MaterializedView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + ], + ), + RuntimeError, + ) + pages = list(client.list_materialized_views(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Convert return value to protobuf type - return_value = instance.AppProfile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +@pytest.mark.asyncio +async def test_list_materialized_views_async_pager(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) - response = client.create_app_profile(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + instance.MaterializedView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_materialized_views( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - expected_params = [ - ( - "appProfileId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + assert len(responses) == 6 + assert all(isinstance(i, instance.MaterializedView) for i in responses) -def test_create_app_profile_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_list_materialized_views_async_pages(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.create_app_profile._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "appProfileId", - "ignoreWarnings", - ) - ) - & set( - ( - "parent", - "appProfileId", - "appProfile", - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + instance.MaterializedView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + ], + ), + RuntimeError, ) - ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_materialized_views(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_create_app_profile_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.UpdateMaterializedViewRequest, + dict, + ], +) +def test_update_materialized_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = instance.AppProfile() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/instances/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - app_profile_id="app_profile_id_value", - app_profile=instance.AppProfile(name="name_value"), - ) - mock_args.update(sample_request) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.AppProfile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_materialized_view(request) - client.create_app_profile(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.UpdateMaterializedViewRequest() + assert args[0] == request - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*/instances/*}/appProfiles" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_create_app_profile_rest_flattened_error(transport: str = "rest"): +def test_update_materialized_view_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_app_profile( - bigtable_instance_admin.CreateAppProfileRequest(), - parent="parent_value", - app_profile_id="app_profile_id_value", - app_profile=instance.AppProfile(name="name_value"), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.UpdateMaterializedViewRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_materialized_view), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client.update_materialized_view(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable_instance_admin.UpdateMaterializedViewRequest() -def test_get_app_profile_rest_use_cached_wrapped_rpc(): +def test_update_materialized_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -10747,185 +11886,369 @@ def test_get_app_profile_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_app_profile in client._transport._wrapped_methods + assert ( + client._transport.update_materialized_view + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_app_profile] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.update_materialized_view + ] = mock_rpc request = {} - client.get_app_profile(request) + client.update_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_app_profile(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_app_profile_rest_required_fields( - request_type=bigtable_instance_admin.GetAppProfileRequest, +@pytest.mark.asyncio +async def test_update_materialized_view_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BigtableInstanceAdminRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.update_materialized_view + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_app_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_materialized_view + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.update_materialized_view(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_app_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + await client.update_materialized_view(request) - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_materialized_view_async( + transport: str = "grpc_asyncio", + request_type=bigtable_instance_admin.UpdateMaterializedViewRequest, +): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = instance.AppProfile() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_materialized_view(request) - # Convert return value to protobuf type - return_value = instance.AppProfile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.UpdateMaterializedViewRequest() + assert args[0] == request - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - response = client.get_app_profile(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_update_materialized_view_async_from_dict(): + await test_update_materialized_view_async(request_type=dict) -def test_get_app_profile_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_update_materialized_view_field_headers(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.get_app_profile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.UpdateMaterializedViewRequest() + request.materialized_view.name = "name_value" -def test_get_app_profile_rest_flattened(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_materialized_view), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_materialized_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "materialized_view.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_materialized_view_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = instance.AppProfile() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.UpdateMaterializedViewRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/instances/sample2/appProfiles/sample3" - } + request.materialized_view.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_materialized_view), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.update_materialized_view(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.AppProfile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.get_app_profile(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "materialized_view.name=name_value", + ) in kw["metadata"] + + +def test_update_materialized_view_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_materialized_view), "__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_materialized_view( + materialized_view=instance.MaterializedView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{name=projects/*/instances/*/appProfiles/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].materialized_view + mock_val = instance.MaterializedView(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val -def test_get_app_profile_rest_flattened_error(transport: str = "rest"): +def test_update_materialized_view_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_app_profile( - bigtable_instance_admin.GetAppProfileRequest(), - name="name_value", + client.update_materialized_view( + bigtable_instance_admin.UpdateMaterializedViewRequest(), + materialized_view=instance.MaterializedView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_app_profiles_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_update_materialized_view_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_materialized_view( + materialized_view=instance.MaterializedView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].materialized_view + mock_val = instance.MaterializedView(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_materialized_view_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_materialized_view( + bigtable_instance_admin.UpdateMaterializedViewRequest(), + materialized_view=instance.MaterializedView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.DeleteMaterializedViewRequest, + dict, + ], +) +def test_delete_materialized_view(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_materialized_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.DeleteMaterializedViewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_materialized_view_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.DeleteMaterializedViewRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_materialized_view), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_materialized_view(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable_instance_admin.DeleteMaterializedViewRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_materialized_view_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_app_profiles in client._transport._wrapped_methods + assert ( + client._transport.delete_materialized_view + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -10933,243 +12256,248 @@ def test_list_app_profiles_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_app_profiles + client._transport.delete_materialized_view ] = mock_rpc - request = {} - client.list_app_profiles(request) + client.delete_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_app_profiles(request) + client.delete_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_app_profiles_rest_required_fields( - request_type=bigtable_instance_admin.ListAppProfilesRequest, +@pytest.mark.asyncio +async def test_delete_materialized_view_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BigtableInstanceAdminRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_app_profiles._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify required fields with default values are now present + # Ensure method has been cached + assert ( + client._client._transport.delete_materialized_view + in client._client._transport._wrapped_methods + ) - jsonified_request["parent"] = "parent_value" + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_materialized_view + ] = mock_rpc - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_app_profiles._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) - jsonified_request.update(unset_fields) + request = {} + await client.delete_materialized_view(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.delete_materialized_view(request) - # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListAppProfilesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListAppProfilesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_delete_materialized_view_async( + transport: str = "grpc_asyncio", + request_type=bigtable_instance_admin.DeleteMaterializedViewRequest, +): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.list_app_profiles(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_materialized_view(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.DeleteMaterializedViewRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert response is None -def test_list_app_profiles_rest_unset_required_fields(): - transport = transports.BigtableInstanceAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.list_app_profiles._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) +@pytest.mark.asyncio +async def test_delete_materialized_view_async_from_dict(): + await test_delete_materialized_view_async(request_type=dict) -def test_list_app_profiles_rest_flattened(): +def test_delete_materialized_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListAppProfilesResponse() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.DeleteMaterializedViewRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/instances/sample2"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_materialized_view), "__call__" + ) as call: + call.return_value = None + client.delete_materialized_view(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListAppProfilesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.list_app_profiles(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_materialized_view_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.DeleteMaterializedViewRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_materialized_view), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_materialized_view(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_materialized_view_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_materialized_view), "__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_materialized_view( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*/instances/*}/appProfiles" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_list_app_profiles_rest_flattened_error(transport: str = "rest"): +def test_delete_materialized_view_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_app_profiles( - bigtable_instance_admin.ListAppProfilesRequest(), - parent="parent_value", + client.delete_materialized_view( + bigtable_instance_admin.DeleteMaterializedViewRequest(), + name="name_value", ) -def test_list_app_profiles_rest_pager(transport: str = "rest"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_delete_materialized_view_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - instance.AppProfile(), - instance.AppProfile(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[], - next_page_token="def", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - instance.AppProfile(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None - # Wrap the values into proper Response objs - response = tuple( - bigtable_instance_admin.ListAppProfilesResponse.to_json(x) for x in response + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_materialized_view( + name="name_value", ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = {"parent": "projects/sample1/instances/sample2"} + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - pager = client.list_app_profiles(request=sample_request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, instance.AppProfile) for i in results) +@pytest.mark.asyncio +async def test_delete_materialized_view_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) - pages = list(client.list_app_profiles(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_materialized_view( + bigtable_instance_admin.DeleteMaterializedViewRequest(), + name="name_value", + ) -def test_update_app_profile_rest_use_cached_wrapped_rpc(): +def test_create_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11183,21 +12511,17 @@ def test_update_app_profile_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_app_profile in client._transport._wrapped_methods - ) + assert client._transport.create_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.update_app_profile - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc request = {} - client.update_app_profile(request) + client.create_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -11206,19 +12530,21 @@ def test_update_app_profile_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_app_profile(request) + client.create_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_app_profile_rest_required_fields( - request_type=bigtable_instance_admin.UpdateAppProfileRequest, +def test_create_instance_rest_required_fields( + request_type=bigtable_instance_admin.CreateInstanceRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} + request_init["parent"] = "" + request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11229,24 +12555,24 @@ def test_update_app_profile_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_app_profile._get_unset_required_fields(jsonified_request) + ).create_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_app_profile._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "ignore_warnings", - "update_mask", - ) - ) + ).create_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11267,7 +12593,7 @@ def test_update_app_profile_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -11279,37 +12605,35 @@ def test_update_app_profile_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_app_profile(request) + response = client.create_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_app_profile_rest_unset_required_fields(): +def test_create_instance_rest_unset_required_fields(): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_app_profile._get_unset_required_fields({}) + unset_fields = transport.create_instance._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "ignoreWarnings", - "updateMask", - ) - ) + set(()) & set( ( - "appProfile", - "updateMask", + "parent", + "instanceId", + "instance", + "clusters", ) ) ) -def test_update_app_profile_rest_flattened(): +def test_create_instance_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11321,16 +12645,14 @@ def test_update_app_profile_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = { - "app_profile": { - "name": "projects/sample1/instances/sample2/appProfiles/sample3" - } - } + sample_request = {"parent": "projects/sample1"} # get truthy value for each flattened field mock_args = dict( - app_profile=instance.AppProfile(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", + instance_id="instance_id_value", + instance=gba_instance.Instance(name="name_value"), + clusters={"key_value": gba_instance.Cluster(name="name_value")}, ) mock_args.update(sample_request) @@ -11340,21 +12662,20 @@ def test_update_app_profile_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_app_profile(**mock_args) + client.create_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{app_profile.name=projects/*/instances/*/appProfiles/*}" - % client.transport._host, - args[1], + "%s/v2/{parent=projects/*}/instances" % client.transport._host, args[1] ) -def test_update_app_profile_rest_flattened_error(transport: str = "rest"): +def test_create_instance_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11363,14 +12684,16 @@ def test_update_app_profile_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_app_profile( - bigtable_instance_admin.UpdateAppProfileRequest(), - app_profile=instance.AppProfile(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_delete_app_profile_rest_use_cached_wrapped_rpc(): + client.create_instance( + bigtable_instance_admin.CreateInstanceRequest(), + parent="parent_value", + instance_id="instance_id_value", + instance=gba_instance.Instance(name="name_value"), + clusters={"key_value": gba_instance.Cluster(name="name_value")}, + ) + + +def test_get_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11384,40 +12707,35 @@ def test_delete_app_profile_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_app_profile in client._transport._wrapped_methods - ) + assert client._transport.get_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.delete_app_profile - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc request = {} - client.delete_app_profile(request) + client.get_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_app_profile(request) + client.get_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_app_profile_rest_required_fields( - request_type=bigtable_instance_admin.DeleteAppProfileRequest, +def test_get_instance_rest_required_fields( + request_type=bigtable_instance_admin.GetInstanceRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} request_init["name"] = "" - request_init["ignore_warnings"] = False request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11425,32 +12743,24 @@ def test_delete_app_profile_rest_required_fields( ) # verify fields with default values are dropped - assert "ignoreWarnings" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_app_profile._get_unset_required_fields(jsonified_request) + ).get_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "ignoreWarnings" in jsonified_request - assert jsonified_request["ignoreWarnings"] == request_init["ignore_warnings"] jsonified_request["name"] = "name_value" - jsonified_request["ignoreWarnings"] = True unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_app_profile._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("ignore_warnings",)) + ).get_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request assert jsonified_request["name"] == "name_value" - assert "ignoreWarnings" in jsonified_request - assert jsonified_request["ignoreWarnings"] == True client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11459,7 +12769,7 @@ def test_delete_app_profile_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = instance.Instance() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -11471,49 +12781,39 @@ def test_delete_app_profile_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_app_profile(request) + response = client.get_instance(request) - expected_params = [ - ( - "ignoreWarnings", - str(False).lower(), - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_app_profile_rest_unset_required_fields(): +def test_get_instance_rest_unset_required_fields(): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_app_profile._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("ignoreWarnings",)) - & set( - ( - "name", - "ignoreWarnings", - ) - ) - ) + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_delete_app_profile_rest_flattened(): +def test_get_instance_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11522,12 +12822,10 @@ def test_delete_app_profile_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = instance.Instance() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/instances/sample2/appProfiles/sample3" - } + sample_request = {"name": "projects/sample1/instances/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -11538,24 +12836,25 @@ def test_delete_app_profile_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_app_profile(**mock_args) + client.get_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=projects/*/instances/*/appProfiles/*}" - % client.transport._host, - args[1], + "%s/v2/{name=projects/*/instances/*}" % client.transport._host, args[1] ) -def test_delete_app_profile_rest_flattened_error(transport: str = "rest"): +def test_get_instance_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11564,13 +12863,13 @@ def test_delete_app_profile_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_app_profile( - bigtable_instance_admin.DeleteAppProfileRequest(), + client.get_instance( + bigtable_instance_admin.GetInstanceRequest(), name="name_value", ) -def test_get_iam_policy_rest_use_cached_wrapped_rpc(): +def test_list_instances_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11584,37 +12883,37 @@ def test_get_iam_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_iam_policy in client._transport._wrapped_methods + assert client._transport.list_instances in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc request = {} - client.get_iam_policy(request) + client.list_instances(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_iam_policy(request) + client.list_instances(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_iam_policy_rest_required_fields( - request_type=iam_policy_pb2.GetIamPolicyRequest, +def test_list_instances_rest_required_fields( + request_type=bigtable_instance_admin.ListInstancesRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["resource"] = "" + request_init["parent"] = "" request = request_type(**request_init) - pb_request = request + pb_request = request_type.pb(request) jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -11623,21 +12922,23 @@ def test_get_iam_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_iam_policy._get_unset_required_fields(jsonified_request) + ).list_instances._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["resource"] = "resource_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_iam_policy._get_unset_required_fields(jsonified_request) + ).list_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_token",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11646,7 +12947,7 @@ def test_get_iam_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = bigtable_instance_admin.ListInstancesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -11655,40 +12956,44 @@ def test_get_iam_policy_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListInstancesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_iam_policy(request) + response = client.list_instances(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_iam_policy_rest_unset_required_fields(): +def test_list_instances_rest_unset_required_fields(): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource",))) + unset_fields = transport.list_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageToken",)) & set(("parent",))) -def test_get_iam_policy_rest_flattened(): +def test_list_instances_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11697,38 +13002,39 @@ def test_get_iam_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = bigtable_instance_admin.ListInstancesResponse() # get arguments that satisfy an http rule for this method - sample_request = {"resource": "projects/sample1/instances/sample2"} + sample_request = {"parent": "projects/sample1"} # get truthy value for each flattened field mock_args = dict( - resource="resource_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListInstancesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(**mock_args) + client.list_instances(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{resource=projects/*/instances/*}:getIamPolicy" - % client.transport._host, - args[1], + "%s/v2/{parent=projects/*}/instances" % client.transport._host, args[1] ) -def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): +def test_list_instances_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11737,13 +13043,13 @@ def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource="resource_value", + client.list_instances( + bigtable_instance_admin.ListInstancesRequest(), + parent="parent_value", ) -def test_set_iam_policy_rest_use_cached_wrapped_rpc(): +def test_update_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11757,37 +13063,35 @@ def test_set_iam_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.set_iam_policy in client._transport._wrapped_methods + assert client._transport.update_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc request = {} - client.set_iam_policy(request) + client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_iam_policy(request) + client.update_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_set_iam_policy_rest_required_fields( - request_type=iam_policy_pb2.SetIamPolicyRequest, -): +def test_update_instance_rest_required_fields(request_type=instance.Instance): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["resource"] = "" + request_init["display_name"] = "" request = request_type(**request_init) - pb_request = request + pb_request = request_type.pb(request) jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -11796,21 +13100,21 @@ def test_set_iam_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).set_iam_policy._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["resource"] = "resource_value" + jsonified_request["displayName"] = "display_name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).set_iam_policy._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" + assert "displayName" in jsonified_request + assert jsonified_request["displayName"] == "display_name_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11819,7 +13123,7 @@ def test_set_iam_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = instance.Instance() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -11828,10 +13132,10 @@ def test_set_iam_policy_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "put", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -11840,106 +13144,47 @@ def test_set_iam_policy_rest_required_fields( response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.set_iam_policy(request) + response = client.update_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_set_iam_policy_rest_unset_required_fields(): +def test_update_instance_rest_unset_required_fields(): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "resource", - "policy", - ) - ) - ) - + unset_fields = transport.update_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("displayName",))) -def test_set_iam_policy_rest_flattened(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() +def test_partial_update_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # get arguments that satisfy an http rule for this method - sample_request = {"resource": "projects/sample1/instances/sample2"} + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # get truthy value for each flattened field - mock_args = dict( - resource="resource_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.set_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{resource=projects/*/instances/*}:setIamPolicy" - % client.transport._host, - args[1], - ) - - -def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource="resource_value", - ) - - -def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.test_iam_permissions in client._transport._wrapped_methods + # Ensure method has been cached + assert ( + client._transport.partial_update_instance + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -11948,32 +13193,34 @@ def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.test_iam_permissions + client._transport.partial_update_instance ] = mock_rpc request = {} - client.test_iam_permissions(request) + client.partial_update_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.test_iam_permissions(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.partial_update_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_test_iam_permissions_rest_required_fields( - request_type=iam_policy_pb2.TestIamPermissionsRequest, +def test_partial_update_instance_rest_required_fields( + request_type=bigtable_instance_admin.PartialUpdateInstanceRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" request = request_type(**request_init) - pb_request = request + pb_request = request_type.pb(request) jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -11982,24 +13229,19 @@ def test_test_iam_permissions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).test_iam_permissions._get_unset_required_fields(jsonified_request) + ).partial_update_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["resource"] = "resource_value" - jsonified_request["permissions"] = "permissions_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).test_iam_permissions._get_unset_required_fields(jsonified_request) + ).partial_update_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == "permissions_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12008,7 +13250,7 @@ def test_test_iam_permissions_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -12017,10 +13259,10 @@ def test_test_iam_permissions_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -12028,37 +13270,37 @@ def test_test_iam_permissions_rest_required_fields( response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.test_iam_permissions(request) + response = client.partial_update_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_test_iam_permissions_rest_unset_required_fields(): +def test_partial_update_instance_rest_unset_required_fields(): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + unset_fields = transport.partial_update_instance._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set(("updateMask",)) & set( ( - "resource", - "permissions", + "instance", + "updateMask", ) ) ) -def test_test_iam_permissions_rest_flattened(): +def test_partial_update_instance_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12067,15 +13309,15 @@ def test_test_iam_permissions_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"resource": "projects/sample1/instances/sample2"} + sample_request = {"instance": {"name": "projects/sample1/instances/sample2"}} # get truthy value for each flattened field mock_args = dict( - resource="resource_value", - permissions=["permissions_value"], + instance=gba_instance.Instance(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -12085,21 +13327,21 @@ def test_test_iam_permissions_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.test_iam_permissions(**mock_args) + client.partial_update_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{resource=projects/*/instances/*}:testIamPermissions" - % client.transport._host, + "%s/v2/{instance.name=projects/*/instances/*}" % client.transport._host, args[1], ) -def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): +def test_partial_update_instance_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12108,14 +13350,14 @@ def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): # 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_pb2.TestIamPermissionsRequest(), - resource="resource_value", - permissions=["permissions_value"], + client.partial_update_instance( + bigtable_instance_admin.PartialUpdateInstanceRequest(), + instance=gba_instance.Instance(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_hot_tablets_rest_use_cached_wrapped_rpc(): +def test_delete_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12129,37 +13371,35 @@ def test_list_hot_tablets_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_hot_tablets in client._transport._wrapped_methods + assert client._transport.delete_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_hot_tablets - ] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc request = {} - client.list_hot_tablets(request) + client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_hot_tablets(request) + client.delete_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_hot_tablets_rest_required_fields( - request_type=bigtable_instance_admin.ListHotTabletsRequest, +def test_delete_instance_rest_required_fields( + request_type=bigtable_instance_admin.DeleteInstanceRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12170,30 +13410,21 @@ def test_list_hot_tablets_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_hot_tablets._get_unset_required_fields(jsonified_request) + ).delete_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_hot_tablets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "end_time", - "page_size", - "page_token", - "start_time", - ) - ) + ).delete_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12202,7 +13433,7 @@ def test_list_hot_tablets_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListHotTabletsResponse() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -12214,50 +13445,36 @@ def test_list_hot_tablets_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListHotTabletsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_hot_tablets(request) + response = client.delete_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_hot_tablets_rest_unset_required_fields(): +def test_delete_instance_rest_unset_required_fields(): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_hot_tablets._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "endTime", - "pageSize", - "pageToken", - "startTime", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_list_hot_tablets_rest_flattened(): +def test_delete_instance_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12266,42 +13483,37 @@ def test_list_hot_tablets_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListHotTabletsResponse() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/instances/sample2/clusters/sample3" - } + sample_request = {"name": "projects/sample1/instances/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListHotTabletsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_hot_tablets(**mock_args) + client.delete_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=projects/*/instances/*/clusters/*}/hotTablets" - % client.transport._host, - args[1], + "%s/v2/{name=projects/*/instances/*}" % client.transport._host, args[1] ) -def test_list_hot_tablets_rest_flattened_error(transport: str = "rest"): +def test_delete_instance_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12310,1246 +13522,7791 @@ def test_list_hot_tablets_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_hot_tablets( - bigtable_instance_admin.ListHotTabletsRequest(), - parent="parent_value", + client.delete_instance( + bigtable_instance_admin.DeleteInstanceRequest(), + name="name_value", ) -def test_list_hot_tablets_rest_pager(transport: str = "rest"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +def test_create_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - instance.HotTablet(), - instance.HotTablet(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[], - next_page_token="def", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - instance.HotTablet(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Wrap the values into proper Response objs - response = tuple( - bigtable_instance_admin.ListHotTabletsResponse.to_json(x) for x in response + # Ensure method has been cached + assert client._transport.create_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values + client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc - sample_request = { - "parent": "projects/sample1/instances/sample2/clusters/sample3" - } + request = {} + client.create_cluster(request) - pager = client.list_hot_tablets(request=sample_request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, instance.HotTablet) for i in results) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - pages = list(client.list_hot_tablets(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.create_cluster(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.BigtableInstanceAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.BigtableInstanceAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BigtableInstanceAdminClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) +def test_create_cluster_rest_required_fields( + request_type=bigtable_instance_admin.CreateClusterRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport - # It is an error to provide an api_key and a transport instance. - transport = transports.BigtableInstanceAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + request_init = {} + request_init["parent"] = "" + request_init["cluster_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BigtableInstanceAdminClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BigtableInstanceAdminClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # verify fields with default values are dropped + assert "clusterId" not in jsonified_request - # It is an error to provide scopes and a transport instance. - transport = transports.BigtableInstanceAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BigtableInstanceAdminClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + jsonified_request["parent"] = "parent_value" + jsonified_request["clusterId"] = "cluster_id_value" -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BigtableInstanceAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = BigtableInstanceAdminClient(transport=transport) - assert client.transport is transport + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cluster_id",)) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == "cluster_id_value" -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BigtableInstanceAdminGrpcTransport( + client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + request = request_type(**request_init) - transport = transports.BigtableInstanceAdminGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -@pytest.mark.parametrize( - "transport_class", - [ - transports.BigtableInstanceAdminGrpcTransport, - transports.BigtableInstanceAdminGrpcAsyncIOTransport, - transports.BigtableInstanceAdminRestTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_cluster(request) -def test_transport_kind_grpc(): - transport = BigtableInstanceAdminClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + expected_params = [ + ( + "clusterId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params -def test_initialize_client_w_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" +def test_create_cluster_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - assert client is not None - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_instance_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + unset_fields = transport.create_cluster._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("clusterId",)) + & set( + ( + "parent", + "clusterId", + "cluster", + ) + ) ) - # Mock the actual call, 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=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.CreateInstanceRequest() - - assert args[0] == request_msg - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_instance_empty_call_grpc(): +def test_create_cluster_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - call.return_value = instance.Instance() - client.get_instance(request=None) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.GetInstanceRequest() + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/instances/sample2"} - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_instances_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=instance.Cluster(name="name_value"), + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - call.return_value = bigtable_instance_admin.ListInstancesResponse() - client.list_instances(request=None) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListInstancesRequest() + client.create_cluster(**mock_args) - assert args[0] == request_msg + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/instances/*}/clusters" % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_instance_empty_call_grpc(): +def test_create_cluster_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - call.return_value = instance.Instance() - client.update_instance(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_cluster( + bigtable_instance_admin.CreateClusterRequest(), + parent="parent_value", + cluster_id="cluster_id_value", + cluster=instance.Cluster(name="name_value"), + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = instance.Instance() - assert args[0] == request_msg +def test_get_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_partial_update_instance_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Ensure method has been cached + assert client._transport.get_cluster in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.partial_update_instance), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.partial_update_instance(request=None) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_cluster] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.PartialUpdateInstanceRequest() + request = {} + client.get_cluster(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.get_cluster(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_instance_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - call.return_value = None - client.delete_instance(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteInstanceRequest() +def test_get_cluster_rest_required_fields( + request_type=bigtable_instance_admin.GetClusterRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport - assert args[0] == request_msg + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + # verify fields with default values are dropped -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_cluster_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_cluster(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.CreateClusterRequest() + jsonified_request["name"] = "name_value" - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_cluster_empty_call_grpc(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: - call.return_value = instance.Cluster() - client.get_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.GetClusterRequest() - - assert args[0] == request_msg + # Designate an appropriate value for the returned response. + return_value = instance.Cluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + response_value = Response() + response_value.status_code = 200 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_clusters_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Convert return value to protobuf type + return_value = instance.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: - call.return_value = bigtable_instance_admin.ListClustersResponse() - client.list_clusters(request=None) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListClustersRequest() + response = client.get_cluster(request) - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_cluster_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_get_cluster_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = instance.Cluster() - - assert args[0] == request_msg + unset_fields = transport.get_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_partial_update_cluster_empty_call_grpc(): +def test_get_cluster_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.partial_update_cluster), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.partial_update_cluster(request=None) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.Cluster() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.PartialUpdateClusterRequest() + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/instances/sample2/clusters/sample3"} - assert args[0] == request_msg + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_cluster_empty_call_grpc(): + client.get_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/instances/*/clusters/*}" % client.transport._host, + args[1], + ) + + +def test_get_cluster_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: - call.return_value = None - client.delete_cluster(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_cluster( + bigtable_instance_admin.GetClusterRequest(), + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteClusterRequest() - assert args[0] == request_msg +def test_list_clusters_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_app_profile_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Ensure method has been cached + assert client._transport.list_clusters in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_app_profile), "__call__" - ) as call: - call.return_value = instance.AppProfile() - client.create_app_profile(request=None) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_clusters] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.CreateAppProfileRequest() + request = {} + client.list_clusters(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.list_clusters(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_app_profile_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: - call.return_value = instance.AppProfile() - client.get_app_profile(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.GetAppProfileRequest() +def test_list_clusters_rest_required_fields( + request_type=bigtable_instance_admin.ListClustersRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport - assert args[0] == request_msg + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + # verify fields with default values are dropped -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_app_profiles_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_clusters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: - call.return_value = bigtable_instance_admin.ListAppProfilesResponse() - client.list_app_profiles(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListAppProfilesRequest() + jsonified_request["parent"] = "parent_value" - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_clusters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_token",)) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_app_profile_empty_call_grpc(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_app_profile), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_app_profile(request=None) + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.UpdateAppProfileRequest() + response_value = Response() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_app_profile_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response = client.list_clusters(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_app_profile), "__call__" - ) as call: - call.return_value = None - client.delete_app_profile(request=None) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteAppProfileRequest() - assert args[0] == request_msg +def test_list_clusters_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + unset_fields = transport.list_clusters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageToken",)) & set(("parent",))) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_iam_policy_empty_call_grpc(): + +def test_list_clusters_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - client.get_iam_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.GetIamPolicyRequest() - - assert args[0] == request_msg + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListClustersResponse() + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/instances/sample2"} -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_set_iam_policy_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - client.set_iam_policy(request=None) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.SetIamPolicyRequest() + client.list_clusters(**mock_args) - assert args[0] == request_msg + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/instances/*}/clusters" % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_test_iam_permissions_empty_call_grpc(): +def test_list_clusters_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_clusters( + bigtable_instance_admin.ListClustersRequest(), + parent="parent_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest() - assert args[0] == request_msg +def test_update_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_hot_tablets_empty_call_grpc(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Ensure method has been cached + assert client._transport.update_cluster in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: - call.return_value = bigtable_instance_admin.ListHotTabletsResponse() - client.list_hot_tablets(request=None) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_cluster] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListHotTabletsRequest() + request = {} + client.update_cluster(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() -def test_transport_kind_grpc_asyncio(): - transport = BigtableInstanceAdminAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + client.update_cluster(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -def test_initialize_client_w_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None +def test_partial_update_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_instance_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Ensure method has been cached + assert ( + client._transport.partial_update_cluster + in client._transport._wrapped_methods ) - await client.create_instance(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.CreateInstanceRequest() + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.partial_update_cluster + ] = mock_rpc - assert args[0] == request_msg + request = {} + client.partial_update_cluster(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_instance_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.Instance( - name="name_value", - display_name="display_name_value", - state=instance.Instance.State.READY, - type_=instance.Instance.Type.PRODUCTION, - satisfies_pzs=True, - ) - ) - await client.get_instance(request=None) + client.partial_update_cluster(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.GetInstanceRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_partial_update_cluster_rest_required_fields( + request_type=bigtable_instance_admin.PartialUpdateClusterRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_instances_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListInstancesResponse( - failed_locations=["failed_locations_value"], - next_page_token="next_page_token_value", - ) - ) - await client.list_instances(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListInstancesRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).partial_update_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).partial_update_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_instance_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # verify required fields with non-default values are left alone - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.Instance( - name="name_value", - display_name="display_name_value", - state=instance.Instance.State.READY, - type_=instance.Instance.Type.PRODUCTION, - satisfies_pzs=True, - ) - ) - await client.update_instance(request=None) + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = instance.Instance() + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_partial_update_instance_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + response = client.partial_update_cluster(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_partial_update_cluster_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.partial_update_instance), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + unset_fields = transport.partial_update_cluster._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "cluster", + "updateMask", + ) ) - await client.partial_update_instance(request=None) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.PartialUpdateInstanceRequest() - assert args[0] == request_msg +def test_partial_update_cluster_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_instance_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # get arguments that satisfy an http rule for this method + sample_request = { + "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} + } - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_instance(request=None) + # get truthy value for each flattened field + mock_args = dict( + cluster=instance.Cluster(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteInstanceRequest() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - assert args[0] == request_msg + client.partial_update_cluster(**mock_args) + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{cluster.name=projects/*/instances/*/clusters/*}" + % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_cluster_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_partial_update_cluster_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.partial_update_cluster( + bigtable_instance_admin.PartialUpdateClusterRequest(), + cluster=instance.Cluster(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - await client.create_cluster(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.CreateClusterRequest() - assert args[0] == request_msg +def test_delete_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_cluster_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert client._transport.delete_cluster in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.Cluster( - name="name_value", - location="location_value", - state=instance.Cluster.State.READY, - serve_nodes=1181, - node_scaling_factor=instance.Cluster.NodeScalingFactor.NODE_SCALING_FACTOR_1X, - default_storage_type=common.StorageType.SSD, - ) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - await client.get_cluster(request=None) + client._transport._wrapped_methods[client._transport.delete_cluster] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.GetClusterRequest() + request = {} + client.delete_cluster(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.delete_cluster(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_clusters_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListClustersResponse( - failed_locations=["failed_locations_value"], - next_page_token="next_page_token_value", - ) - ) - await client.list_clusters(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListClustersRequest() +def test_delete_cluster_rest_required_fields( + request_type=bigtable_instance_admin.DeleteClusterRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport - assert args[0] == request_msg + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + # verify fields with default values are dropped -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_cluster_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.update_cluster(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = instance.Cluster() + jsonified_request["name"] = "name_value" - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_partial_update_cluster_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.partial_update_cluster), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.partial_update_cluster(request=None) + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.PartialUpdateClusterRequest() + response_value = Response() + response_value.status_code = 200 + json_return_value = "" - assert args[0] == request_msg + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_cluster(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_cluster_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_cluster(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteClusterRequest() +def test_delete_cluster_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - assert args[0] == request_msg + unset_fields = transport.delete_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_app_profile_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_cluster_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_app_profile), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.AppProfile( - name="name_value", - etag="etag_value", - description="description_value", - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - await client.create_app_profile(request=None) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.CreateAppProfileRequest() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - assert args[0] == request_msg + client.delete_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/instances/*/clusters/*}" % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_app_profile_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_cluster_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.AppProfile( - name="name_value", - etag="etag_value", - description="description_value", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_cluster( + bigtable_instance_admin.DeleteClusterRequest(), + name="name_value", ) - await client.get_app_profile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.GetAppProfileRequest() - assert args[0] == request_msg +def test_create_app_profile_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_app_profiles_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListAppProfilesResponse( - next_page_token="next_page_token_value", - failed_locations=["failed_locations_value"], - ) + # Ensure method has been cached + assert ( + client._transport.create_app_profile in client._transport._wrapped_methods ) - await client.list_app_profiles(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListAppProfilesRequest() + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_app_profile + ] = mock_rpc - assert args[0] == request_msg + request = {} + client.create_app_profile(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_app_profile_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.create_app_profile(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_app_profile), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.update_app_profile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.UpdateAppProfileRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_create_app_profile_rest_required_fields( + request_type=bigtable_instance_admin.CreateAppProfileRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_app_profile_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request_init["parent"] = "" + request_init["app_profile_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_app_profile), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_app_profile(request=None) + # verify fields with default values are dropped + assert "appProfileId" not in jsonified_request - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteAppProfileRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_app_profile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + assert "appProfileId" in jsonified_request + assert jsonified_request["appProfileId"] == request_init["app_profile_id"] + jsonified_request["parent"] = "parent_value" + jsonified_request["appProfileId"] = "app_profile_id_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_iam_policy_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_app_profile._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "app_profile_id", + "ignore_warnings", + ) ) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - await client.get_iam_policy(request=None) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "appProfileId" in jsonified_request + assert jsonified_request["appProfileId"] == "app_profile_id_value" - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.GetIamPolicyRequest() + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) - assert args[0] == request_msg + # Designate an appropriate value for the returned response. + return_value = instance.AppProfile() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + response_value = Response() + response_value.status_code = 200 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_set_iam_policy_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Convert return value to protobuf type + return_value = instance.AppProfile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - await client.set_iam_policy(request=None) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.SetIamPolicyRequest() + response = client.create_app_profile(request) - assert args[0] == request_msg + expected_params = [ + ( + "appProfileId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_create_app_profile_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], + unset_fields = transport.create_app_profile._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "appProfileId", + "ignoreWarnings", ) ) - await client.test_iam_permissions(request=None) + & set( + ( + "parent", + "appProfileId", + "appProfile", + ) + ) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest() - assert args[0] == request_msg +def test_create_app_profile_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.AppProfile() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_hot_tablets_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/instances/sample2"} - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListHotTabletsResponse( - next_page_token="next_page_token_value", - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + app_profile_id="app_profile_id_value", + app_profile=instance.AppProfile(name="name_value"), ) - await client.list_hot_tablets(request=None) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListHotTabletsRequest() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.AppProfile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - assert args[0] == request_msg + client.create_app_profile(**mock_args) + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/instances/*}/appProfiles" + % client.transport._host, + args[1], + ) -def test_transport_kind_rest(): - transport = BigtableInstanceAdminClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) + +def test_create_app_profile_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_app_profile( + bigtable_instance_admin.CreateAppProfileRequest(), + parent="parent_value", + app_profile_id="app_profile_id_value", + app_profile=instance.AppProfile(name="name_value"), + ) + + +def test_get_app_profile_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_app_profile in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_app_profile] = mock_rpc + + request = {} + client.get_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_app_profile(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_app_profile_rest_required_fields( + request_type=bigtable_instance_admin.GetAppProfileRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_app_profile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_app_profile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = instance.AppProfile() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.AppProfile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_app_profile(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_app_profile_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_app_profile._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_app_profile_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.AppProfile() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/instances/sample2/appProfiles/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.AppProfile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_app_profile(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/instances/*/appProfiles/*}" + % client.transport._host, + args[1], + ) + + +def test_get_app_profile_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_app_profile( + bigtable_instance_admin.GetAppProfileRequest(), + name="name_value", + ) + + +def test_list_app_profiles_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_app_profiles in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_app_profiles + ] = mock_rpc + + request = {} + client.list_app_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_app_profiles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_app_profiles_rest_required_fields( + request_type=bigtable_instance_admin.ListAppProfilesRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_app_profiles._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_app_profiles._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListAppProfilesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListAppProfilesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_app_profiles(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_app_profiles_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_app_profiles._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_app_profiles_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListAppProfilesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/instances/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListAppProfilesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_app_profiles(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/instances/*}/appProfiles" + % client.transport._host, + args[1], + ) + + +def test_list_app_profiles_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_app_profiles( + bigtable_instance_admin.ListAppProfilesRequest(), + parent="parent_value", + ) + + +def test_list_app_profiles_rest_pager(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + instance.AppProfile(), + instance.AppProfile(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[], + next_page_token="def", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + instance.AppProfile(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + bigtable_instance_admin.ListAppProfilesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/instances/sample2"} + + pager = client.list_app_profiles(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.AppProfile) for i in results) + + pages = list(client.list_app_profiles(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_app_profile_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_app_profile in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_app_profile + ] = mock_rpc + + request = {} + client.update_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_app_profile(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_app_profile_rest_required_fields( + request_type=bigtable_instance_admin.UpdateAppProfileRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_app_profile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_app_profile._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "ignore_warnings", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_app_profile(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_app_profile_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_app_profile._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "ignoreWarnings", + "updateMask", + ) + ) + & set( + ( + "appProfile", + "updateMask", + ) + ) + ) + + +def test_update_app_profile_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "app_profile": { + "name": "projects/sample1/instances/sample2/appProfiles/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + app_profile=instance.AppProfile(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_app_profile(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{app_profile.name=projects/*/instances/*/appProfiles/*}" + % client.transport._host, + args[1], + ) + + +def test_update_app_profile_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_app_profile( + bigtable_instance_admin.UpdateAppProfileRequest(), + app_profile=instance.AppProfile(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_app_profile_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_app_profile in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_app_profile + ] = mock_rpc + + request = {} + client.delete_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_app_profile(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_app_profile_rest_required_fields( + request_type=bigtable_instance_admin.DeleteAppProfileRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["name"] = "" + request_init["ignore_warnings"] = False + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "ignoreWarnings" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_app_profile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "ignoreWarnings" in jsonified_request + assert jsonified_request["ignoreWarnings"] == request_init["ignore_warnings"] + + jsonified_request["name"] = "name_value" + jsonified_request["ignoreWarnings"] = True + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_app_profile._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("ignore_warnings",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "ignoreWarnings" in jsonified_request + assert jsonified_request["ignoreWarnings"] == True + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_app_profile(request) + + expected_params = [ + ( + "ignoreWarnings", + str(False).lower(), + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_app_profile_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_app_profile._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("ignoreWarnings",)) + & set( + ( + "name", + "ignoreWarnings", + ) + ) + ) + + +def test_delete_app_profile_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/instances/sample2/appProfiles/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ignore_warnings=True, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_app_profile(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/instances/*/appProfiles/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_app_profile_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_app_profile( + bigtable_instance_admin.DeleteAppProfileRequest(), + name="name_value", + ignore_warnings=True, + ) + + +def test_get_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource",))) + + +def test_get_iam_policy_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "projects/sample1/instances/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + resource="resource_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{resource=projects/*/instances/*}:getIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", + ) + + +def test_set_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "policy", + ) + ) + ) + + +def test_set_iam_policy_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "projects/sample1/instances/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + resource="resource_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{resource=projects/*/instances/*}:setIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", + ) + + +def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.test_iam_permissions in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.test_iam_permissions + ] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_iam_permissions_rest_required_fields( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + jsonified_request["permissions"] = "permissions_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == "permissions_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "permissions", + ) + ) + ) + + +def test_test_iam_permissions_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "projects/sample1/instances/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + resource="resource_value", + permissions=["permissions_value"], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{resource=projects/*/instances/*}:testIamPermissions" + % client.transport._host, + args[1], + ) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_list_hot_tablets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_hot_tablets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_hot_tablets + ] = mock_rpc + + request = {} + client.list_hot_tablets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_hot_tablets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_hot_tablets_rest_required_fields( + request_type=bigtable_instance_admin.ListHotTabletsRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_hot_tablets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_hot_tablets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "end_time", + "page_size", + "page_token", + "start_time", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListHotTabletsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListHotTabletsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_hot_tablets(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_hot_tablets_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_hot_tablets._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "endTime", + "pageSize", + "pageToken", + "startTime", + ) + ) + & set(("parent",)) + ) + + +def test_list_hot_tablets_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListHotTabletsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/instances/sample2/clusters/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListHotTabletsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_hot_tablets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/instances/*/clusters/*}/hotTablets" + % client.transport._host, + args[1], + ) + + +def test_list_hot_tablets_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_hot_tablets( + bigtable_instance_admin.ListHotTabletsRequest(), + parent="parent_value", + ) + + +def test_list_hot_tablets_rest_pager(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + instance.HotTablet(), + instance.HotTablet(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[], + next_page_token="def", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + instance.HotTablet(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + bigtable_instance_admin.ListHotTabletsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/instances/sample2/clusters/sample3" + } + + pager = client.list_hot_tablets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.HotTablet) for i in results) + + pages = list(client.list_hot_tablets(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_logical_view_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_logical_view in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_logical_view + ] = mock_rpc + + request = {} + client.create_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_logical_view(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_logical_view_rest_required_fields( + request_type=bigtable_instance_admin.CreateLogicalViewRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["logical_view_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "logicalViewId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_logical_view._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "logicalViewId" in jsonified_request + assert jsonified_request["logicalViewId"] == request_init["logical_view_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["logicalViewId"] = "logical_view_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_logical_view._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("logical_view_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "logicalViewId" in jsonified_request + assert jsonified_request["logicalViewId"] == "logical_view_id_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_logical_view(request) + + expected_params = [ + ( + "logicalViewId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_logical_view_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_logical_view._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("logicalViewId",)) + & set( + ( + "parent", + "logicalViewId", + "logicalView", + ) + ) + ) + + +def test_create_logical_view_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/instances/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + logical_view=instance.LogicalView(name="name_value"), + logical_view_id="logical_view_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_logical_view(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/instances/*}/logicalViews" + % client.transport._host, + args[1], + ) + + +def test_create_logical_view_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_logical_view( + bigtable_instance_admin.CreateLogicalViewRequest(), + parent="parent_value", + logical_view=instance.LogicalView(name="name_value"), + logical_view_id="logical_view_id_value", + ) + + +def test_get_logical_view_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_logical_view in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_logical_view + ] = mock_rpc + + request = {} + client.get_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_logical_view(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_logical_view_rest_required_fields( + request_type=bigtable_instance_admin.GetLogicalViewRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_logical_view._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_logical_view._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = instance.LogicalView() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.LogicalView.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_logical_view(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_logical_view_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_logical_view._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_logical_view_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.LogicalView() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/instances/sample2/logicalViews/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.LogicalView.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_logical_view(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/instances/*/logicalViews/*}" + % client.transport._host, + args[1], + ) + + +def test_get_logical_view_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_logical_view( + bigtable_instance_admin.GetLogicalViewRequest(), + name="name_value", + ) + + +def test_list_logical_views_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_logical_views in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_logical_views + ] = mock_rpc + + request = {} + client.list_logical_views(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_logical_views(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_logical_views_rest_required_fields( + request_type=bigtable_instance_admin.ListLogicalViewsRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_logical_views._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_logical_views._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListLogicalViewsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListLogicalViewsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_logical_views(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_logical_views_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_logical_views._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_logical_views_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListLogicalViewsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/instances/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListLogicalViewsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_logical_views(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/instances/*}/logicalViews" + % client.transport._host, + args[1], + ) + + +def test_list_logical_views_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_logical_views( + bigtable_instance_admin.ListLogicalViewsRequest(), + parent="parent_value", + ) + + +def test_list_logical_views_rest_pager(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + instance.LogicalView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + bigtable_instance_admin.ListLogicalViewsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/instances/sample2"} + + pager = client.list_logical_views(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.LogicalView) for i in results) + + pages = list(client.list_logical_views(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_logical_view_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_logical_view in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_logical_view + ] = mock_rpc + + request = {} + client.update_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_logical_view(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_logical_view_rest_required_fields( + request_type=bigtable_instance_admin.UpdateLogicalViewRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_logical_view._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_logical_view._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_logical_view(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_logical_view_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_logical_view._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("logicalView",))) + + +def test_update_logical_view_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "logical_view": { + "name": "projects/sample1/instances/sample2/logicalViews/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + logical_view=instance.LogicalView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_logical_view(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{logical_view.name=projects/*/instances/*/logicalViews/*}" + % client.transport._host, + args[1], + ) + + +def test_update_logical_view_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_logical_view( + bigtable_instance_admin.UpdateLogicalViewRequest(), + logical_view=instance.LogicalView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_logical_view_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_logical_view in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_logical_view + ] = mock_rpc + + request = {} + client.delete_logical_view(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_logical_view(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_logical_view_rest_required_fields( + request_type=bigtable_instance_admin.DeleteLogicalViewRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_logical_view._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_logical_view._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_logical_view(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_logical_view_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_logical_view._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_logical_view_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/instances/sample2/logicalViews/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_logical_view(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/instances/*/logicalViews/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_logical_view_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_logical_view( + bigtable_instance_admin.DeleteLogicalViewRequest(), + name="name_value", + ) + + +def test_create_materialized_view_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_materialized_view + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_materialized_view + ] = mock_rpc + + request = {} + client.create_materialized_view(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_materialized_view(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_materialized_view_rest_required_fields( + request_type=bigtable_instance_admin.CreateMaterializedViewRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["materialized_view_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "materializedViewId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_materialized_view._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "materializedViewId" in jsonified_request + assert ( + jsonified_request["materializedViewId"] == request_init["materialized_view_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["materializedViewId"] = "materialized_view_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_materialized_view._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("materialized_view_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "materializedViewId" in jsonified_request + assert jsonified_request["materializedViewId"] == "materialized_view_id_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_materialized_view(request) + + expected_params = [ + ( + "materializedViewId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_materialized_view_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_materialized_view._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("materializedViewId",)) + & set( + ( + "parent", + "materializedViewId", + "materializedView", + ) + ) + ) + + +def test_create_materialized_view_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/instances/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + materialized_view=instance.MaterializedView(name="name_value"), + materialized_view_id="materialized_view_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_materialized_view(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/instances/*}/materializedViews" + % client.transport._host, + args[1], + ) + + +def test_create_materialized_view_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_materialized_view( + bigtable_instance_admin.CreateMaterializedViewRequest(), + parent="parent_value", + materialized_view=instance.MaterializedView(name="name_value"), + materialized_view_id="materialized_view_id_value", + ) + + +def test_get_materialized_view_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_materialized_view + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_materialized_view + ] = mock_rpc + + request = {} + client.get_materialized_view(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_materialized_view(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_materialized_view_rest_required_fields( + request_type=bigtable_instance_admin.GetMaterializedViewRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_materialized_view._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_materialized_view._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = instance.MaterializedView() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.MaterializedView.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_materialized_view(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_materialized_view_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_materialized_view._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_materialized_view_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.MaterializedView() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/instances/sample2/materializedViews/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.MaterializedView.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_materialized_view(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/instances/*/materializedViews/*}" + % client.transport._host, + args[1], + ) + + +def test_get_materialized_view_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_materialized_view( + bigtable_instance_admin.GetMaterializedViewRequest(), + name="name_value", + ) + + +def test_list_materialized_views_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_materialized_views + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_materialized_views + ] = mock_rpc + + request = {} + client.list_materialized_views(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_materialized_views(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_materialized_views_rest_required_fields( + request_type=bigtable_instance_admin.ListMaterializedViewsRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_materialized_views._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_materialized_views._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListMaterializedViewsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListMaterializedViewsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_materialized_views(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_materialized_views_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_materialized_views._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_materialized_views_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListMaterializedViewsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/instances/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListMaterializedViewsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_materialized_views(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/instances/*}/materializedViews" + % client.transport._host, + args[1], + ) + + +def test_list_materialized_views_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_materialized_views( + bigtable_instance_admin.ListMaterializedViewsRequest(), + parent="parent_value", + ) + + +def test_list_materialized_views_rest_pager(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + instance.MaterializedView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + bigtable_instance_admin.ListMaterializedViewsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/instances/sample2"} + + pager = client.list_materialized_views(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.MaterializedView) for i in results) + + pages = list(client.list_materialized_views(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_materialized_view_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_materialized_view + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_materialized_view + ] = mock_rpc + + request = {} + client.update_materialized_view(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_materialized_view(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_materialized_view_rest_required_fields( + request_type=bigtable_instance_admin.UpdateMaterializedViewRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_materialized_view._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_materialized_view._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_materialized_view(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_materialized_view_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_materialized_view._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("materializedView",))) + + +def test_update_materialized_view_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "materialized_view": { + "name": "projects/sample1/instances/sample2/materializedViews/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + materialized_view=instance.MaterializedView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_materialized_view(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{materialized_view.name=projects/*/instances/*/materializedViews/*}" + % client.transport._host, + args[1], + ) + + +def test_update_materialized_view_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_materialized_view( + bigtable_instance_admin.UpdateMaterializedViewRequest(), + materialized_view=instance.MaterializedView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_materialized_view_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_materialized_view + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_materialized_view + ] = mock_rpc + + request = {} + client.delete_materialized_view(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_materialized_view(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_materialized_view_rest_required_fields( + request_type=bigtable_instance_admin.DeleteMaterializedViewRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_materialized_view._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_materialized_view._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_materialized_view(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_materialized_view_rest_unset_required_fields(): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_materialized_view._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_materialized_view_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/instances/sample2/materializedViews/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_materialized_view(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/instances/*/materializedViews/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_materialized_view_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_materialized_view( + bigtable_instance_admin.DeleteMaterializedViewRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BigtableInstanceAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BigtableInstanceAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BigtableInstanceAdminClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BigtableInstanceAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BigtableInstanceAdminClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BigtableInstanceAdminClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BigtableInstanceAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BigtableInstanceAdminClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BigtableInstanceAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BigtableInstanceAdminClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BigtableInstanceAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BigtableInstanceAdminGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BigtableInstanceAdminGrpcTransport, + transports.BigtableInstanceAdminGrpcAsyncIOTransport, + transports.BigtableInstanceAdminRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = BigtableInstanceAdminClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, 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=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = instance.Instance() + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = bigtable_instance_admin.ListInstancesResponse() + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + call.return_value = instance.Instance() + client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.Instance() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_partial_update_instance_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.partial_update_instance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.partial_update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.PartialUpdateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = None + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_cluster_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_cluster_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: + call.return_value = instance.Cluster() + client.get_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_clusters_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: + call.return_value = bigtable_instance_admin.ListClustersResponse() + client.list_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_cluster_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.Cluster() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_partial_update_cluster_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.partial_update_cluster), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.partial_update_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.PartialUpdateClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_cluster_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: + call.return_value = None + client.delete_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_app_profile_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_app_profile), "__call__" + ) as call: + call.return_value = instance.AppProfile() + client.create_app_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateAppProfileRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_app_profile_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: + call.return_value = instance.AppProfile() + client.get_app_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetAppProfileRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_app_profiles_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: + call.return_value = bigtable_instance_admin.ListAppProfilesResponse() + client.list_app_profiles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListAppProfilesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_app_profile_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_app_profile), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_app_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateAppProfileRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_app_profile_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_profile), "__call__" + ) as call: + call.return_value = None + client.delete_app_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteAppProfileRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_hot_tablets_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + call.return_value = bigtable_instance_admin.ListHotTabletsResponse() + client.list_hot_tablets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListHotTabletsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_logical_view_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_logical_view_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + call.return_value = instance.LogicalView() + client.get_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_logical_views_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + call.return_value = bigtable_instance_admin.ListLogicalViewsResponse() + client.list_logical_views(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListLogicalViewsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_logical_view_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_logical_view), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_logical_view_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_logical_view), "__call__" + ) as call: + call.return_value = None + client.delete_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_materialized_view_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateMaterializedViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_materialized_view_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + call.return_value = instance.MaterializedView() + client.get_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetMaterializedViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_materialized_views_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() + client.list_materialized_views(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListMaterializedViewsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_materialized_view_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_materialized_view), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateMaterializedViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_materialized_view_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_materialized_view), "__call__" + ) as call: + call.return_value = None + client.delete_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteMaterializedViewRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = BigtableInstanceAdminAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_instance_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_instance_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.Instance( + name="name_value", + display_name="display_name_value", + state=instance.Instance.State.READY, + type_=instance.Instance.Type.PRODUCTION, + satisfies_pzs=True, + satisfies_pzi=True, + ) + ) + await client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_instances_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListInstancesResponse( + failed_locations=["failed_locations_value"], + next_page_token="next_page_token_value", + ) + ) + await client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_instance_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.Instance( + name="name_value", + display_name="display_name_value", + state=instance.Instance.State.READY, + type_=instance.Instance.Type.PRODUCTION, + satisfies_pzs=True, + satisfies_pzi=True, + ) + ) + await client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.Instance() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_partial_update_instance_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.partial_update_instance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.partial_update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.PartialUpdateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_instance_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_cluster_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_cluster_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.Cluster( + name="name_value", + location="location_value", + state=instance.Cluster.State.READY, + serve_nodes=1181, + node_scaling_factor=instance.Cluster.NodeScalingFactor.NODE_SCALING_FACTOR_1X, + default_storage_type=common.StorageType.SSD, + ) + ) + await client.get_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_clusters_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListClustersResponse( + failed_locations=["failed_locations_value"], + next_page_token="next_page_token_value", + ) + ) + await client.list_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_cluster_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.Cluster() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_partial_update_cluster_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.partial_update_cluster), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.partial_update_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.PartialUpdateClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_cluster_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_app_profile_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.AppProfile( + name="name_value", + etag="etag_value", + description="description_value", + ) + ) + await client.create_app_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateAppProfileRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_app_profile_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.AppProfile( + name="name_value", + etag="etag_value", + description="description_value", + ) + ) + await client.get_app_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetAppProfileRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_app_profiles_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListAppProfilesResponse( + next_page_token="next_page_token_value", + failed_locations=["failed_locations_value"], + ) + ) + await client.list_app_profiles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListAppProfilesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_app_profile_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_app_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateAppProfileRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_app_profile_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_app_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteAppProfileRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_iam_policy_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_iam_policy_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_hot_tablets_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListHotTabletsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_hot_tablets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListHotTabletsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_logical_view_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_logical_view_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.LogicalView( + name="name_value", + query="query_value", + etag="etag_value", + ) + ) + await client.get_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_logical_views_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListLogicalViewsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_logical_views(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListLogicalViewsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_logical_view_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_logical_view_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_logical_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_materialized_view_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateMaterializedViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_materialized_view_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.MaterializedView( + name="name_value", + query="query_value", + etag="etag_value", + deletion_protection=True, + ) + ) + await client.get_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetMaterializedViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_materialized_views_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListMaterializedViewsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_materialized_views(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListMaterializedViewsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_materialized_view_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateMaterializedViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_materialized_view_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteMaterializedViewRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BigtableInstanceAdminClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) assert transport.kind == "rest" -def test_create_instance_rest_bad_request( - request_type=bigtable_instance_admin.CreateInstanceRequest, +def test_create_instance_rest_bad_request( + request_type=bigtable_instance_admin.CreateInstanceRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_create_instance" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_create_instance_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_create_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.CreateInstanceRequest.pb( + bigtable_instance_admin.CreateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = bigtable_instance_admin.CreateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_instance_rest_bad_request( + request_type=bigtable_instance_admin.GetInstanceRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.GetInstanceRequest, + dict, + ], +) +def test_get_instance_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.Instance( + name="name_value", + display_name="display_name_value", + state=instance.Instance.State.READY, + type_=instance.Instance.Type.PRODUCTION, + satisfies_pzs=True, + satisfies_pzi=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Instance) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.state == instance.Instance.State.READY + assert response.type_ == instance.Instance.Type.PRODUCTION + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_get_instance" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_get_instance_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_get_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.GetInstanceRequest.pb( + bigtable_instance_admin.GetInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.Instance.to_json(instance.Instance()) + req.return_value.content = return_value + + request = bigtable_instance_admin.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.Instance() + post_with_metadata.return_value = instance.Instance(), metadata + + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_instances_rest_bad_request( + request_type=bigtable_instance_admin.ListInstancesRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_instances(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.ListInstancesRequest, + dict, + ], +) +def test_list_instances_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListInstancesResponse( + failed_locations=["failed_locations_value"], + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_instances(request) + + assert response.raw_page is response + + # Establish that the response is the type that we expect. + assert isinstance(response, bigtable_instance_admin.ListInstancesResponse) + assert response.failed_locations == ["failed_locations_value"] + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_list_instances" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_list_instances_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_list_instances" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.ListInstancesRequest.pb( + bigtable_instance_admin.ListInstancesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = bigtable_instance_admin.ListInstancesResponse.to_json( + bigtable_instance_admin.ListInstancesResponse() + ) + req.return_value.content = return_value + + request = bigtable_instance_admin.ListInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigtable_instance_admin.ListInstancesResponse() + post_with_metadata.return_value = ( + bigtable_instance_admin.ListInstancesResponse(), + metadata, + ) + + client.list_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_instance_rest_bad_request(request_type=instance.Instance): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.Instance, + dict, + ], +) +def test_update_instance_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.Instance( + name="name_value", + display_name="display_name_value", + state=instance.Instance.State.READY, + type_=instance.Instance.Type.PRODUCTION, + satisfies_pzs=True, + satisfies_pzi=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Instance) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.state == instance.Instance.State.READY + assert response.type_ == instance.Instance.Type.PRODUCTION + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_update_instance" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_update_instance_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_update_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = instance.Instance.pb(instance.Instance()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.Instance.to_json(instance.Instance()) + req.return_value.content = return_value + + request = instance.Instance() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.Instance() + post_with_metadata.return_value = instance.Instance(), metadata + + client.update_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_partial_update_instance_rest_bad_request( + request_type=bigtable_instance_admin.PartialUpdateInstanceRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"instance": {"name": "projects/sample1/instances/sample2"}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.partial_update_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.PartialUpdateInstanceRequest, + dict, + ], +) +def test_partial_update_instance_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"instance": {"name": "projects/sample1/instances/sample2"}} + request_init["instance"] = { + "name": "projects/sample1/instances/sample2", + "display_name": "display_name_value", + "state": 1, + "type_": 1, + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "satisfies_pzs": True, + "satisfies_pzi": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = bigtable_instance_admin.PartialUpdateInstanceRequest.meta.fields[ + "instance" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.partial_update_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_partial_update_instance_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_partial_update_instance" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_partial_update_instance_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_partial_update_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.PartialUpdateInstanceRequest.pb( + bigtable_instance_admin.PartialUpdateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = bigtable_instance_admin.PartialUpdateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.partial_update_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_instance_rest_bad_request( + request_type=bigtable_instance_admin.DeleteInstanceRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_instance(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_delete_instance" + ) as pre: + pre.assert_not_called() + pb_message = bigtable_instance_admin.DeleteInstanceRequest.pb( + bigtable_instance_admin.DeleteInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = bigtable_instance_admin.DeleteInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_create_cluster_rest_bad_request( + request_type=bigtable_instance_admin.CreateClusterRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_cluster(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.CreateClusterRequest, + dict, + ], +) +def test_create_cluster_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/instances/sample2"} + request_init["cluster"] = { + "name": "name_value", + "location": "location_value", + "state": 1, + "serve_nodes": 1181, + "node_scaling_factor": 1, + "cluster_config": { + "cluster_autoscaling_config": { + "autoscaling_limits": { + "min_serve_nodes": 1600, + "max_serve_nodes": 1602, + }, + "autoscaling_targets": { + "cpu_utilization_percent": 2483, + "storage_utilization_gib_per_node": 3404, + }, + } + }, + "default_storage_type": 1, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = bigtable_instance_admin.CreateClusterRequest.meta.fields["cluster"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_cluster_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_create_cluster" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_create_cluster_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_create_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.CreateClusterRequest.pb( + bigtable_instance_admin.CreateClusterRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = bigtable_instance_admin.CreateClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_cluster_rest_bad_request( + request_type=bigtable_instance_admin.GetClusterRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_cluster(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.GetClusterRequest, + dict, + ], +) +def test_get_cluster_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.Cluster( + name="name_value", + location="location_value", + state=instance.Cluster.State.READY, + serve_nodes=1181, + node_scaling_factor=instance.Cluster.NodeScalingFactor.NODE_SCALING_FACTOR_1X, + default_storage_type=common.StorageType.SSD, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Cluster) + assert response.name == "name_value" + assert response.location == "location_value" + assert response.state == instance.Cluster.State.READY + assert response.serve_nodes == 1181 + assert ( + response.node_scaling_factor + == instance.Cluster.NodeScalingFactor.NODE_SCALING_FACTOR_1X + ) + assert response.default_storage_type == common.StorageType.SSD + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_get_cluster" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_get_cluster_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_get_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.GetClusterRequest.pb( + bigtable_instance_admin.GetClusterRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.Cluster.to_json(instance.Cluster()) + req.return_value.content = return_value + + request = bigtable_instance_admin.GetClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.Cluster() + post_with_metadata.return_value = instance.Cluster(), metadata + + client.get_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_clusters_rest_bad_request( + request_type=bigtable_instance_admin.ListClustersRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} + request_init = {"parent": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -13563,44 +21320,56 @@ def test_create_instance_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.create_instance(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_clusters(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateInstanceRequest, + bigtable_instance_admin.ListClustersRequest, dict, ], ) -def test_create_instance_rest_call_success(request_type): +def test_list_clusters_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} + request_init = {"parent": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = bigtable_instance_admin.ListClustersResponse( + failed_locations=["failed_locations_value"], + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_clusters(request) + + assert response.raw_page is response # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, bigtable_instance_admin.ListClustersResponse) + assert response.failed_locations == ["failed_locations_value"] + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): +def test_list_clusters_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13614,16 +21383,18 @@ def test_create_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_create_instance" + transports.BigtableInstanceAdminRestInterceptor, "post_list_clusters" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_create_instance" + transports.BigtableInstanceAdminRestInterceptor, + "post_list_clusters_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_list_clusters" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.CreateInstanceRequest.pb( - bigtable_instance_admin.CreateInstanceRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.ListClustersRequest.pb( + bigtable_instance_admin.ListClustersRequest() ) transcode.return_value = { "method": "post", @@ -13634,18 +21405,25 @@ def test_create_instance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = bigtable_instance_admin.ListClustersResponse.to_json( + bigtable_instance_admin.ListClustersResponse() + ) req.return_value.content = return_value - request = bigtable_instance_admin.CreateInstanceRequest() + request = bigtable_instance_admin.ListClustersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = bigtable_instance_admin.ListClustersResponse() + post_with_metadata.return_value = ( + bigtable_instance_admin.ListClustersResponse(), + metadata, + ) - client.create_instance( + client.list_clusters( request, metadata=[ ("key", "val"), @@ -13655,16 +21433,15 @@ def test_create_instance_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_instance_rest_bad_request( - request_type=bigtable_instance_admin.GetInstanceRequest, -): +def test_update_cluster_rest_bad_request(request_type=instance.Cluster): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2"} + request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -13678,58 +21455,46 @@ def test_get_instance_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.get_instance(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_cluster(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetInstanceRequest, + instance.Cluster, dict, ], ) -def test_get_instance_rest_call_success(request_type): +def test_update_cluster_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2"} + request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = instance.Instance( - name="name_value", - display_name="display_name_value", - state=instance.Instance.State.READY, - type_=instance.Instance.Type.PRODUCTION, - satisfies_pzs=True, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_instance(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_cluster(request) # Establish that the response is the type that we expect. - assert isinstance(response, instance.Instance) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.state == instance.Instance.State.READY - assert response.type_ == instance.Instance.Type.PRODUCTION - assert response.satisfies_pzs is True + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): +def test_update_cluster_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13743,15 +21508,19 @@ def test_get_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_get_instance" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_update_cluster" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_get_instance" + transports.BigtableInstanceAdminRestInterceptor, + "post_update_cluster_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_update_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.GetInstanceRequest.pb( - bigtable_instance_admin.GetInstanceRequest() - ) + post_with_metadata.assert_not_called() + pb_message = instance.Cluster.pb(instance.Cluster()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13761,18 +21530,20 @@ def test_get_instance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = instance.Instance.to_json(instance.Instance()) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = bigtable_instance_admin.GetInstanceRequest() + request = instance.Cluster() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = instance.Instance() + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_instance( + client.update_cluster( request, metadata=[ ("key", "val"), @@ -13782,16 +21553,19 @@ def test_get_instance_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_list_instances_rest_bad_request( - request_type=bigtable_instance_admin.ListInstancesRequest, +def test_partial_update_cluster_rest_bad_request( + request_type=bigtable_instance_admin.PartialUpdateClusterRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} + request_init = { + "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -13805,54 +21579,138 @@ def test_list_instances_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.list_instances(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.partial_update_cluster(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListInstancesRequest, + bigtable_instance_admin.PartialUpdateClusterRequest, dict, ], ) -def test_list_instances_rest_call_success(request_type): +def test_partial_update_cluster_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} + request_init = { + "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} + } + request_init["cluster"] = { + "name": "projects/sample1/instances/sample2/clusters/sample3", + "location": "location_value", + "state": 1, + "serve_nodes": 1181, + "node_scaling_factor": 1, + "cluster_config": { + "cluster_autoscaling_config": { + "autoscaling_limits": { + "min_serve_nodes": 1600, + "max_serve_nodes": 1602, + }, + "autoscaling_targets": { + "cpu_utilization_percent": 2483, + "storage_utilization_gib_per_node": 3404, + }, + } + }, + "default_storage_type": 1, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = bigtable_instance_admin.PartialUpdateClusterRequest.meta.fields[ + "cluster" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListInstancesResponse( - failed_locations=["failed_locations_value"], - next_page_token="next_page_token_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListInstancesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_instances(request) - - assert response.raw_page is response + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.partial_update_cluster(request) # Establish that the response is the type that we expect. - assert isinstance(response, bigtable_instance_admin.ListInstancesResponse) - assert response.failed_locations == ["failed_locations_value"] - assert response.next_page_token == "next_page_token_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): +def test_partial_update_cluster_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13866,14 +21724,20 @@ def test_list_instances_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_list_instances" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_partial_update_cluster" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_list_instances" + transports.BigtableInstanceAdminRestInterceptor, + "post_partial_update_cluster_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_partial_update_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.ListInstancesRequest.pb( - bigtable_instance_admin.ListInstancesRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.PartialUpdateClusterRequest.pb( + bigtable_instance_admin.PartialUpdateClusterRequest() ) transcode.return_value = { "method": "post", @@ -13884,20 +21748,20 @@ def test_list_instances_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = bigtable_instance_admin.ListInstancesResponse.to_json( - bigtable_instance_admin.ListInstancesResponse() - ) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = bigtable_instance_admin.ListInstancesRequest() + request = bigtable_instance_admin.PartialUpdateClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = bigtable_instance_admin.ListInstancesResponse() + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.list_instances( + client.partial_update_cluster( request, metadata=[ ("key", "val"), @@ -13907,14 +21771,17 @@ def test_list_instances_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_update_instance_rest_bad_request(request_type=instance.Instance): +def test_delete_cluster_rest_bad_request( + request_type=bigtable_instance_admin.DeleteClusterRequest, +): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2"} + request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -13928,58 +21795,46 @@ def test_update_instance_rest_bad_request(request_type=instance.Instance): response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.update_instance(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_cluster(request) @pytest.mark.parametrize( "request_type", [ - instance.Instance, + bigtable_instance_admin.DeleteClusterRequest, dict, ], ) -def test_update_instance_rest_call_success(request_type): +def test_delete_cluster_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2"} + request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = instance.Instance( - name="name_value", - display_name="display_name_value", - state=instance.Instance.State.READY, - type_=instance.Instance.Type.PRODUCTION, - satisfies_pzs=True, - ) + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_instance(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_cluster(request) # Establish that the response is the type that we expect. - assert isinstance(response, instance.Instance) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.state == instance.Instance.State.READY - assert response.type_ == instance.Instance.Type.PRODUCTION - assert response.satisfies_pzs is True + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): +def test_delete_cluster_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13993,13 +21848,12 @@ def test_update_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_update_instance" - ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_update_instance" + transports.BigtableInstanceAdminRestInterceptor, "pre_delete_cluster" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = instance.Instance.pb(instance.Instance()) + pb_message = bigtable_instance_admin.DeleteClusterRequest.pb( + bigtable_instance_admin.DeleteClusterRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14009,18 +21863,16 @@ def test_update_instance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = instance.Instance.to_json(instance.Instance()) - req.return_value.content = return_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - request = instance.Instance() + request = bigtable_instance_admin.DeleteClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = instance.Instance() - client.update_instance( + client.delete_cluster( request, metadata=[ ("key", "val"), @@ -14029,17 +21881,16 @@ def test_update_instance_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_partial_update_instance_rest_bad_request( - request_type=bigtable_instance_admin.PartialUpdateInstanceRequest, +def test_create_app_profile_rest_bad_request( + request_type=bigtable_instance_admin.CreateAppProfileRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"instance": {"name": "projects/sample1/instances/sample2"}} + request_init = {"parent": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14053,39 +21904,47 @@ def test_partial_update_instance_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.partial_update_instance(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_app_profile(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.PartialUpdateInstanceRequest, + bigtable_instance_admin.CreateAppProfileRequest, dict, ], ) -def test_partial_update_instance_rest_call_success(request_type): +def test_create_app_profile_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"instance": {"name": "projects/sample1/instances/sample2"}} - request_init["instance"] = { - "name": "projects/sample1/instances/sample2", - "display_name": "display_name_value", - "state": 1, - "type_": 1, - "labels": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "satisfies_pzs": True, + request_init = {"parent": "projects/sample1/instances/sample2"} + request_init["app_profile"] = { + "name": "name_value", + "etag": "etag_value", + "description": "description_value", + "multi_cluster_routing_use_any": { + "cluster_ids": ["cluster_ids_value1", "cluster_ids_value2"], + "row_affinity": {}, + }, + "single_cluster_routing": { + "cluster_id": "cluster_id_value", + "allow_transactional_writes": True, + }, + "priority": 1, + "standard_isolation": {"priority": 1}, + "data_boost_isolation_read_only": {"compute_billing_owner": 1}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = bigtable_instance_admin.PartialUpdateInstanceRequest.meta.fields[ - "instance" + test_field = bigtable_instance_admin.CreateAppProfileRequest.meta.fields[ + "app_profile" ] def get_message_fields(field): @@ -14114,7 +21973,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER + for field, value in request_init["app_profile"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14144,31 +22003,43 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] + for i in range(0, len(request_init["app_profile"][field])): + del request_init["app_profile"][field][i][subfield] else: - del request_init["instance"][field][subfield] + del request_init["app_profile"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = instance.AppProfile( + name="name_value", + etag="etag_value", + description="description_value", + priority=instance.AppProfile.Priority.PRIORITY_LOW, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.AppProfile.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.partial_update_instance(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_app_profile(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, instance.AppProfile) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.description == "description_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_partial_update_instance_rest_interceptors(null_interceptor): +def test_create_app_profile_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14182,16 +22053,18 @@ def test_partial_update_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_partial_update_instance" + transports.BigtableInstanceAdminRestInterceptor, "post_create_app_profile" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_partial_update_instance" + transports.BigtableInstanceAdminRestInterceptor, + "post_create_app_profile_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_create_app_profile" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.PartialUpdateInstanceRequest.pb( - bigtable_instance_admin.PartialUpdateInstanceRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.CreateAppProfileRequest.pb( + bigtable_instance_admin.CreateAppProfileRequest() ) transcode.return_value = { "method": "post", @@ -14202,18 +22075,153 @@ def test_partial_update_instance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.AppProfile.to_json(instance.AppProfile()) + req.return_value.content = return_value + + request = bigtable_instance_admin.CreateAppProfileRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.AppProfile() + post_with_metadata.return_value = instance.AppProfile(), metadata + + client.create_app_profile( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_app_profile_rest_bad_request( + request_type=bigtable_instance_admin.GetAppProfileRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2/appProfiles/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_app_profile(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.GetAppProfileRequest, + dict, + ], +) +def test_get_app_profile_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2/appProfiles/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.AppProfile( + name="name_value", + etag="etag_value", + description="description_value", + priority=instance.AppProfile.Priority.PRIORITY_LOW, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.AppProfile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_app_profile(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.AppProfile) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.description == "description_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_app_profile_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_get_app_profile" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_get_app_profile_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_get_app_profile" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.GetAppProfileRequest.pb( + bigtable_instance_admin.GetAppProfileRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.AppProfile.to_json(instance.AppProfile()) req.return_value.content = return_value - request = bigtable_instance_admin.PartialUpdateInstanceRequest() + request = bigtable_instance_admin.GetAppProfileRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = instance.AppProfile() + post_with_metadata.return_value = instance.AppProfile(), metadata - client.partial_update_instance( + client.get_app_profile( request, metadata=[ ("key", "val"), @@ -14223,16 +22231,17 @@ def test_partial_update_instance_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_delete_instance_rest_bad_request( - request_type=bigtable_instance_admin.DeleteInstanceRequest, +def test_list_app_profiles_rest_bad_request( + request_type=bigtable_instance_admin.ListAppProfilesRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2"} + request_init = {"parent": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14246,44 +22255,54 @@ def test_delete_instance_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.delete_instance(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_app_profiles(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.DeleteInstanceRequest, + bigtable_instance_admin.ListAppProfilesRequest, dict, ], ) -def test_delete_instance_rest_call_success(request_type): +def test_list_app_profiles_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2"} + request_init = {"parent": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = bigtable_instance_admin.ListAppProfilesResponse( + next_page_token="next_page_token_value", + failed_locations=["failed_locations_value"], + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListAppProfilesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_instance(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_app_profiles(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, pagers.ListAppProfilesPager) + assert response.next_page_token == "next_page_token_value" + assert response.failed_locations == ["failed_locations_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): +def test_list_app_profiles_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14297,11 +22316,18 @@ def test_delete_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_delete_instance" + transports.BigtableInstanceAdminRestInterceptor, "post_list_app_profiles" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_list_app_profiles_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_list_app_profiles" ) as pre: pre.assert_not_called() - pb_message = bigtable_instance_admin.DeleteInstanceRequest.pb( - bigtable_instance_admin.DeleteInstanceRequest() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.ListAppProfilesRequest.pb( + bigtable_instance_admin.ListAppProfilesRequest() ) transcode.return_value = { "method": "post", @@ -14312,15 +22338,25 @@ def test_delete_instance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = bigtable_instance_admin.ListAppProfilesResponse.to_json( + bigtable_instance_admin.ListAppProfilesResponse() + ) + req.return_value.content = return_value - request = bigtable_instance_admin.DeleteInstanceRequest() + request = bigtable_instance_admin.ListAppProfilesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = bigtable_instance_admin.ListAppProfilesResponse() + post_with_metadata.return_value = ( + bigtable_instance_admin.ListAppProfilesResponse(), + metadata, + ) - client.delete_instance( + client.list_app_profiles( request, metadata=[ ("key", "val"), @@ -14329,16 +22365,22 @@ def test_delete_instance_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_create_cluster_rest_bad_request( - request_type=bigtable_instance_admin.CreateClusterRequest, +def test_update_app_profile_rest_bad_request( + request_type=bigtable_instance_admin.UpdateAppProfileRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/instances/sample2"} + request_init = { + "app_profile": { + "name": "projects/sample1/instances/sample2/appProfiles/sample3" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14352,50 +22394,52 @@ def test_create_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.create_cluster(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_app_profile(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateClusterRequest, + bigtable_instance_admin.UpdateAppProfileRequest, dict, ], ) -def test_create_cluster_rest_call_success(request_type): +def test_update_app_profile_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/instances/sample2"} - request_init["cluster"] = { - "name": "name_value", - "location": "location_value", - "state": 1, - "serve_nodes": 1181, - "node_scaling_factor": 1, - "cluster_config": { - "cluster_autoscaling_config": { - "autoscaling_limits": { - "min_serve_nodes": 1600, - "max_serve_nodes": 1602, - }, - "autoscaling_targets": { - "cpu_utilization_percent": 2483, - "storage_utilization_gib_per_node": 3404, - }, - } + request_init = { + "app_profile": { + "name": "projects/sample1/instances/sample2/appProfiles/sample3" + } + } + request_init["app_profile"] = { + "name": "projects/sample1/instances/sample2/appProfiles/sample3", + "etag": "etag_value", + "description": "description_value", + "multi_cluster_routing_use_any": { + "cluster_ids": ["cluster_ids_value1", "cluster_ids_value2"], + "row_affinity": {}, }, - "default_storage_type": 1, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "single_cluster_routing": { + "cluster_id": "cluster_id_value", + "allow_transactional_writes": True, + }, + "priority": 1, + "standard_isolation": {"priority": 1}, + "data_boost_isolation_read_only": {"compute_billing_owner": 1}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = bigtable_instance_admin.CreateClusterRequest.meta.fields["cluster"] + test_field = bigtable_instance_admin.UpdateAppProfileRequest.meta.fields[ + "app_profile" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -14423,7 +22467,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["cluster"].items(): # pragma: NO COVER + for field, value in request_init["app_profile"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14453,10 +22497,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["cluster"][field])): - del request_init["cluster"][field][i][subfield] + for i in range(0, len(request_init["app_profile"][field])): + del request_init["app_profile"][field][i][subfield] else: - del request_init["cluster"][field][subfield] + del request_init["app_profile"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -14470,14 +22514,15 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_cluster(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_app_profile(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_cluster_rest_interceptors(null_interceptor): +def test_update_app_profile_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14493,14 +22538,18 @@ def test_create_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_create_cluster" + transports.BigtableInstanceAdminRestInterceptor, "post_update_app_profile" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_create_cluster" + transports.BigtableInstanceAdminRestInterceptor, + "post_update_app_profile_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_update_app_profile" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.CreateClusterRequest.pb( - bigtable_instance_admin.CreateClusterRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.UpdateAppProfileRequest.pb( + bigtable_instance_admin.UpdateAppProfileRequest() ) transcode.return_value = { "method": "post", @@ -14511,18 +22560,20 @@ def test_create_cluster_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = bigtable_instance_admin.CreateClusterRequest() + request = bigtable_instance_admin.UpdateAppProfileRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_cluster( + client.update_app_profile( request, metadata=[ ("key", "val"), @@ -14532,16 +22583,17 @@ def test_create_cluster_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_cluster_rest_bad_request( - request_type=bigtable_instance_admin.GetClusterRequest, +def test_delete_app_profile_rest_bad_request( + request_type=bigtable_instance_admin.DeleteAppProfileRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request_init = {"name": "projects/sample1/instances/sample2/appProfiles/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14555,63 +22607,46 @@ def test_get_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.get_cluster(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_app_profile(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetClusterRequest, + bigtable_instance_admin.DeleteAppProfileRequest, dict, ], ) -def test_get_cluster_rest_call_success(request_type): +def test_delete_app_profile_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request_init = {"name": "projects/sample1/instances/sample2/appProfiles/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = instance.Cluster( - name="name_value", - location="location_value", - state=instance.Cluster.State.READY, - serve_nodes=1181, - node_scaling_factor=instance.Cluster.NodeScalingFactor.NODE_SCALING_FACTOR_1X, - default_storage_type=common.StorageType.SSD, - ) + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = instance.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_cluster(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_app_profile(request) # Establish that the response is the type that we expect. - assert isinstance(response, instance.Cluster) - assert response.name == "name_value" - assert response.location == "location_value" - assert response.state == instance.Cluster.State.READY - assert response.serve_nodes == 1181 - assert ( - response.node_scaling_factor - == instance.Cluster.NodeScalingFactor.NODE_SCALING_FACTOR_1X - ) - assert response.default_storage_type == common.StorageType.SSD + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_cluster_rest_interceptors(null_interceptor): +def test_delete_app_profile_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14625,14 +22660,11 @@ def test_get_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_get_cluster" - ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_get_cluster" + transports.BigtableInstanceAdminRestInterceptor, "pre_delete_app_profile" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = bigtable_instance_admin.GetClusterRequest.pb( - bigtable_instance_admin.GetClusterRequest() + pb_message = bigtable_instance_admin.DeleteAppProfileRequest.pb( + bigtable_instance_admin.DeleteAppProfileRequest() ) transcode.return_value = { "method": "post", @@ -14643,18 +22675,16 @@ def test_get_cluster_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = instance.Cluster.to_json(instance.Cluster()) - req.return_value.content = return_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - request = bigtable_instance_admin.GetClusterRequest() + request = bigtable_instance_admin.DeleteAppProfileRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = instance.Cluster() - client.get_cluster( + client.delete_app_profile( request, metadata=[ ("key", "val"), @@ -14663,17 +22693,16 @@ def test_get_cluster_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_list_clusters_rest_bad_request( - request_type=bigtable_instance_admin.ListClustersRequest, +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/instances/sample2"} + request_init = {"resource": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14687,54 +22716,51 @@ def test_list_clusters_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.list_clusters(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListClustersRequest, + iam_policy_pb2.GetIamPolicyRequest, dict, ], ) -def test_list_clusters_rest_call_success(request_type): +def test_get_iam_policy_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/instances/sample2"} + request_init = {"resource": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListClustersResponse( - failed_locations=["failed_locations_value"], - next_page_token="next_page_token_value", + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_clusters(request) - - assert response.raw_page is response + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_iam_policy(request) # Establish that the response is the type that we expect. - assert isinstance(response, bigtable_instance_admin.ListClustersResponse) - assert response.failed_locations == ["failed_locations_value"] - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_clusters_rest_interceptors(null_interceptor): +def test_get_iam_policy_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14748,15 +22774,17 @@ def test_list_clusters_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_list_clusters" + transports.BigtableInstanceAdminRestInterceptor, "post_get_iam_policy" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_list_clusters" + transports.BigtableInstanceAdminRestInterceptor, + "post_get_iam_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_get_iam_policy" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.ListClustersRequest.pb( - bigtable_instance_admin.ListClustersRequest() - ) + post_with_metadata.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14766,20 +22794,20 @@ def test_list_clusters_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = bigtable_instance_admin.ListClustersResponse.to_json( - bigtable_instance_admin.ListClustersResponse() - ) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(policy_pb2.Policy()) req.return_value.content = return_value - request = bigtable_instance_admin.ListClustersRequest() + request = iam_policy_pb2.GetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = bigtable_instance_admin.ListClustersResponse() + post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata - client.list_clusters( + client.get_iam_policy( request, metadata=[ ("key", "val"), @@ -14789,14 +22817,17 @@ def test_list_clusters_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_update_cluster_rest_bad_request(request_type=instance.Cluster): +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request_init = {"resource": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14810,29 +22841,33 @@ def test_update_cluster_rest_bad_request(request_type=instance.Cluster): response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.update_cluster(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - instance.Cluster, + iam_policy_pb2.SetIamPolicyRequest, dict, ], ) -def test_update_cluster_rest_call_success(request_type): +def test_set_iam_policy_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request_init = {"resource": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -14840,14 +22875,17 @@ def test_update_cluster_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_cluster(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.set_iam_policy(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_cluster_rest_interceptors(null_interceptor): +def test_set_iam_policy_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14861,15 +22899,17 @@ def test_update_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_update_cluster" + transports.BigtableInstanceAdminRestInterceptor, "post_set_iam_policy" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_update_cluster" + transports.BigtableInstanceAdminRestInterceptor, + "post_set_iam_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_set_iam_policy" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = instance.Cluster.pb(instance.Cluster()) + post_with_metadata.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14879,18 +22919,20 @@ def test_update_cluster_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(policy_pb2.Policy()) req.return_value.content = return_value - request = instance.Cluster() + request = iam_policy_pb2.SetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata - client.update_cluster( + client.set_iam_policy( request, metadata=[ ("key", "val"), @@ -14900,18 +22942,17 @@ def test_update_cluster_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_partial_update_cluster_rest_bad_request( - request_type=bigtable_instance_admin.PartialUpdateClusterRequest, +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} - } + request_init = {"resource": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14925,121 +22966,32 @@ def test_partial_update_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.partial_update_cluster(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.PartialUpdateClusterRequest, + iam_policy_pb2.TestIamPermissionsRequest, dict, ], ) -def test_partial_update_cluster_rest_call_success(request_type): +def test_test_iam_permissions_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} - } - request_init["cluster"] = { - "name": "projects/sample1/instances/sample2/clusters/sample3", - "location": "location_value", - "state": 1, - "serve_nodes": 1181, - "node_scaling_factor": 1, - "cluster_config": { - "cluster_autoscaling_config": { - "autoscaling_limits": { - "min_serve_nodes": 1600, - "max_serve_nodes": 1602, - }, - "autoscaling_targets": { - "cpu_utilization_percent": 2483, - "storage_utilization_gib_per_node": 3404, - }, - } - }, - "default_storage_type": 1, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = bigtable_instance_admin.PartialUpdateClusterRequest.meta.fields[ - "cluster" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["cluster"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["cluster"][field])): - del request_init["cluster"][field][i][subfield] - else: - del request_init["cluster"][field][subfield] + request_init = {"resource": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -15047,14 +22999,16 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.partial_update_cluster(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.test_iam_permissions(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_partial_update_cluster_rest_interceptors(null_interceptor): +def test_test_iam_permissions_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15068,17 +23022,17 @@ def test_partial_update_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_partial_update_cluster" + transports.BigtableInstanceAdminRestInterceptor, "post_test_iam_permissions" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_partial_update_cluster" + transports.BigtableInstanceAdminRestInterceptor, + "post_test_iam_permissions_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_test_iam_permissions" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.PartialUpdateClusterRequest.pb( - bigtable_instance_admin.PartialUpdateClusterRequest() - ) + post_with_metadata.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15088,18 +23042,25 @@ def test_partial_update_cluster_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() + ) req.return_value.content = return_value - request = bigtable_instance_admin.PartialUpdateClusterRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + post_with_metadata.return_value = ( + iam_policy_pb2.TestIamPermissionsResponse(), + metadata, + ) - client.partial_update_cluster( + client.test_iam_permissions( request, metadata=[ ("key", "val"), @@ -15109,16 +23070,17 @@ def test_partial_update_cluster_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_delete_cluster_rest_bad_request( - request_type=bigtable_instance_admin.DeleteClusterRequest, +def test_list_hot_tablets_rest_bad_request( + request_type=bigtable_instance_admin.ListHotTabletsRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/instances/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15132,44 +23094,52 @@ def test_delete_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.delete_cluster(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_hot_tablets(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.DeleteClusterRequest, + bigtable_instance_admin.ListHotTabletsRequest, dict, ], ) -def test_delete_cluster_rest_call_success(request_type): +def test_list_hot_tablets_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/instances/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = bigtable_instance_admin.ListHotTabletsResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListHotTabletsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_cluster(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_hot_tablets(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, pagers.ListHotTabletsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_cluster_rest_interceptors(null_interceptor): +def test_list_hot_tablets_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15183,11 +23153,18 @@ def test_delete_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_delete_cluster" + transports.BigtableInstanceAdminRestInterceptor, "post_list_hot_tablets" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_list_hot_tablets_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_list_hot_tablets" ) as pre: pre.assert_not_called() - pb_message = bigtable_instance_admin.DeleteClusterRequest.pb( - bigtable_instance_admin.DeleteClusterRequest() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.ListHotTabletsRequest.pb( + bigtable_instance_admin.ListHotTabletsRequest() ) transcode.return_value = { "method": "post", @@ -15198,15 +23175,25 @@ def test_delete_cluster_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = bigtable_instance_admin.ListHotTabletsResponse.to_json( + bigtable_instance_admin.ListHotTabletsResponse() + ) + req.return_value.content = return_value - request = bigtable_instance_admin.DeleteClusterRequest() + request = bigtable_instance_admin.ListHotTabletsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = bigtable_instance_admin.ListHotTabletsResponse() + post_with_metadata.return_value = ( + bigtable_instance_admin.ListHotTabletsResponse(), + metadata, + ) - client.delete_cluster( + client.list_hot_tablets( request, metadata=[ ("key", "val"), @@ -15215,10 +23202,12 @@ def test_delete_cluster_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_create_app_profile_rest_bad_request( - request_type=bigtable_instance_admin.CreateAppProfileRequest, +def test_create_logical_view_rest_bad_request( + request_type=bigtable_instance_admin.CreateLogicalViewRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -15238,46 +23227,36 @@ def test_create_app_profile_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.create_app_profile(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_logical_view(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateAppProfileRequest, + bigtable_instance_admin.CreateLogicalViewRequest, dict, ], ) -def test_create_app_profile_rest_call_success(request_type): +def test_create_logical_view_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/instances/sample2"} - request_init["app_profile"] = { + request_init["logical_view"] = { "name": "name_value", + "query": "query_value", "etag": "etag_value", - "description": "description_value", - "multi_cluster_routing_use_any": { - "cluster_ids": ["cluster_ids_value1", "cluster_ids_value2"], - "row_affinity": {}, - }, - "single_cluster_routing": { - "cluster_id": "cluster_id_value", - "allow_transactional_writes": True, - }, - "priority": 1, - "standard_isolation": {"priority": 1}, - "data_boost_isolation_read_only": {"compute_billing_owner": 1}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = bigtable_instance_admin.CreateAppProfileRequest.meta.fields[ - "app_profile" + test_field = bigtable_instance_admin.CreateLogicalViewRequest.meta.fields[ + "logical_view" ] def get_message_fields(field): @@ -15306,7 +23285,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["app_profile"].items(): # pragma: NO COVER + for field, value in request_init["logical_view"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -15336,42 +23315,32 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["app_profile"][field])): - del request_init["app_profile"][field][i][subfield] + for i in range(0, len(request_init["logical_view"][field])): + del request_init["logical_view"][field][i][subfield] else: - del request_init["app_profile"][field][subfield] + del request_init["logical_view"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = instance.AppProfile( - name="name_value", - etag="etag_value", - description="description_value", - priority=instance.AppProfile.Priority.PRIORITY_LOW, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = instance.AppProfile.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_app_profile(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_logical_view(request) # Establish that the response is the type that we expect. - assert isinstance(response, instance.AppProfile) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.description == "description_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_app_profile_rest_interceptors(null_interceptor): +def test_create_logical_view_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15385,14 +23354,20 @@ def test_create_app_profile_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_create_app_profile" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_create_logical_view" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_create_app_profile" + transports.BigtableInstanceAdminRestInterceptor, + "post_create_logical_view_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_create_logical_view" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.CreateAppProfileRequest.pb( - bigtable_instance_admin.CreateAppProfileRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.CreateLogicalViewRequest.pb( + bigtable_instance_admin.CreateLogicalViewRequest() ) transcode.return_value = { "method": "post", @@ -15403,18 +23378,20 @@ def test_create_app_profile_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = instance.AppProfile.to_json(instance.AppProfile()) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = bigtable_instance_admin.CreateAppProfileRequest() + request = bigtable_instance_admin.CreateLogicalViewRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = instance.AppProfile() + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_app_profile( + client.create_logical_view( request, metadata=[ ("key", "val"), @@ -15424,16 +23401,17 @@ def test_create_app_profile_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_app_profile_rest_bad_request( - request_type=bigtable_instance_admin.GetAppProfileRequest, +def test_get_logical_view_rest_bad_request( + request_type=bigtable_instance_admin.GetLogicalViewRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/appProfiles/sample3"} + request_init = {"name": "projects/sample1/instances/sample2/logicalViews/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15447,33 +23425,33 @@ def test_get_app_profile_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.get_app_profile(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_logical_view(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetAppProfileRequest, + bigtable_instance_admin.GetLogicalViewRequest, dict, ], ) -def test_get_app_profile_rest_call_success(request_type): +def test_get_logical_view_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/appProfiles/sample3"} + request_init = {"name": "projects/sample1/instances/sample2/logicalViews/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = instance.AppProfile( + return_value = instance.LogicalView( name="name_value", + query="query_value", etag="etag_value", - description="description_value", - priority=instance.AppProfile.Priority.PRIORITY_LOW, ) # Wrap the value into a proper Response obj @@ -15481,21 +23459,22 @@ def test_get_app_profile_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = instance.AppProfile.pb(return_value) + return_value = instance.LogicalView.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_app_profile(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_logical_view(request) # Establish that the response is the type that we expect. - assert isinstance(response, instance.AppProfile) + assert isinstance(response, instance.LogicalView) assert response.name == "name_value" + assert response.query == "query_value" assert response.etag == "etag_value" - assert response.description == "description_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_app_profile_rest_interceptors(null_interceptor): +def test_get_logical_view_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15509,14 +23488,18 @@ def test_get_app_profile_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_get_app_profile" + transports.BigtableInstanceAdminRestInterceptor, "post_get_logical_view" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_get_app_profile" + transports.BigtableInstanceAdminRestInterceptor, + "post_get_logical_view_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_get_logical_view" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.GetAppProfileRequest.pb( - bigtable_instance_admin.GetAppProfileRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.GetLogicalViewRequest.pb( + bigtable_instance_admin.GetLogicalViewRequest() ) transcode.return_value = { "method": "post", @@ -15527,18 +23510,20 @@ def test_get_app_profile_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = instance.AppProfile.to_json(instance.AppProfile()) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.LogicalView.to_json(instance.LogicalView()) req.return_value.content = return_value - request = bigtable_instance_admin.GetAppProfileRequest() + request = bigtable_instance_admin.GetLogicalViewRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = instance.AppProfile() + post.return_value = instance.LogicalView() + post_with_metadata.return_value = instance.LogicalView(), metadata - client.get_app_profile( + client.get_logical_view( request, metadata=[ ("key", "val"), @@ -15548,10 +23533,11 @@ def test_get_app_profile_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_list_app_profiles_rest_bad_request( - request_type=bigtable_instance_admin.ListAppProfilesRequest, +def test_list_logical_views_rest_bad_request( + request_type=bigtable_instance_admin.ListLogicalViewsRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -15571,17 +23557,18 @@ def test_list_app_profiles_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.list_app_profiles(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_logical_views(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListAppProfilesRequest, + bigtable_instance_admin.ListLogicalViewsRequest, dict, ], ) -def test_list_app_profiles_rest_call_success(request_type): +def test_list_logical_views_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -15593,9 +23580,8 @@ def test_list_app_profiles_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListAppProfilesResponse( + return_value = bigtable_instance_admin.ListLogicalViewsResponse( next_page_token="next_page_token_value", - failed_locations=["failed_locations_value"], ) # Wrap the value into a proper Response obj @@ -15603,20 +23589,20 @@ def test_list_app_profiles_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListAppProfilesResponse.pb(return_value) + return_value = bigtable_instance_admin.ListLogicalViewsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_app_profiles(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_logical_views(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAppProfilesPager) + assert isinstance(response, pagers.ListLogicalViewsPager) assert response.next_page_token == "next_page_token_value" - assert response.failed_locations == ["failed_locations_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_app_profiles_rest_interceptors(null_interceptor): +def test_list_logical_views_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15630,14 +23616,18 @@ def test_list_app_profiles_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_list_app_profiles" + transports.BigtableInstanceAdminRestInterceptor, "post_list_logical_views" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_list_app_profiles" + transports.BigtableInstanceAdminRestInterceptor, + "post_list_logical_views_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_list_logical_views" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.ListAppProfilesRequest.pb( - bigtable_instance_admin.ListAppProfilesRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.ListLogicalViewsRequest.pb( + bigtable_instance_admin.ListLogicalViewsRequest() ) transcode.return_value = { "method": "post", @@ -15648,20 +23638,25 @@ def test_list_app_profiles_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = bigtable_instance_admin.ListAppProfilesResponse.to_json( - bigtable_instance_admin.ListAppProfilesResponse() + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = bigtable_instance_admin.ListLogicalViewsResponse.to_json( + bigtable_instance_admin.ListLogicalViewsResponse() ) req.return_value.content = return_value - request = bigtable_instance_admin.ListAppProfilesRequest() + request = bigtable_instance_admin.ListLogicalViewsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = bigtable_instance_admin.ListAppProfilesResponse() + post.return_value = bigtable_instance_admin.ListLogicalViewsResponse() + post_with_metadata.return_value = ( + bigtable_instance_admin.ListLogicalViewsResponse(), + metadata, + ) - client.list_app_profiles( + client.list_logical_views( request, metadata=[ ("key", "val"), @@ -15671,18 +23666,19 @@ def test_list_app_profiles_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_update_app_profile_rest_bad_request( - request_type=bigtable_instance_admin.UpdateAppProfileRequest, +def test_update_logical_view_rest_bad_request( + request_type=bigtable_instance_admin.UpdateLogicalViewRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "app_profile": { - "name": "projects/sample1/instances/sample2/appProfiles/sample3" + "logical_view": { + "name": "projects/sample1/instances/sample2/logicalViews/sample3" } } request = request_type(**request_init) @@ -15698,50 +23694,40 @@ def test_update_app_profile_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.update_app_profile(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_logical_view(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.UpdateAppProfileRequest, + bigtable_instance_admin.UpdateLogicalViewRequest, dict, ], ) -def test_update_app_profile_rest_call_success(request_type): +def test_update_logical_view_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "app_profile": { - "name": "projects/sample1/instances/sample2/appProfiles/sample3" + "logical_view": { + "name": "projects/sample1/instances/sample2/logicalViews/sample3" } } - request_init["app_profile"] = { - "name": "projects/sample1/instances/sample2/appProfiles/sample3", + request_init["logical_view"] = { + "name": "projects/sample1/instances/sample2/logicalViews/sample3", + "query": "query_value", "etag": "etag_value", - "description": "description_value", - "multi_cluster_routing_use_any": { - "cluster_ids": ["cluster_ids_value1", "cluster_ids_value2"], - "row_affinity": {}, - }, - "single_cluster_routing": { - "cluster_id": "cluster_id_value", - "allow_transactional_writes": True, - }, - "priority": 1, - "standard_isolation": {"priority": 1}, - "data_boost_isolation_read_only": {"compute_billing_owner": 1}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = bigtable_instance_admin.UpdateAppProfileRequest.meta.fields[ - "app_profile" + test_field = bigtable_instance_admin.UpdateLogicalViewRequest.meta.fields[ + "logical_view" ] def get_message_fields(field): @@ -15770,7 +23756,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["app_profile"].items(): # pragma: NO COVER + for field, value in request_init["logical_view"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -15800,10 +23786,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["app_profile"][field])): - del request_init["app_profile"][field][i][subfield] + for i in range(0, len(request_init["logical_view"][field])): + del request_init["logical_view"][field][i][subfield] else: - del request_init["app_profile"][field][subfield] + del request_init["logical_view"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -15817,14 +23803,15 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_app_profile(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_logical_view(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_app_profile_rest_interceptors(null_interceptor): +def test_update_logical_view_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15840,14 +23827,18 @@ def test_update_app_profile_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_update_app_profile" + transports.BigtableInstanceAdminRestInterceptor, "post_update_logical_view" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_update_app_profile" + transports.BigtableInstanceAdminRestInterceptor, + "post_update_logical_view_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_update_logical_view" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = bigtable_instance_admin.UpdateAppProfileRequest.pb( - bigtable_instance_admin.UpdateAppProfileRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.UpdateLogicalViewRequest.pb( + bigtable_instance_admin.UpdateLogicalViewRequest() ) transcode.return_value = { "method": "post", @@ -15858,18 +23849,20 @@ def test_update_app_profile_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = bigtable_instance_admin.UpdateAppProfileRequest() + request = bigtable_instance_admin.UpdateLogicalViewRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_app_profile( + client.update_logical_view( request, metadata=[ ("key", "val"), @@ -15879,67 +23872,254 @@ def test_update_app_profile_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_delete_app_profile_rest_bad_request( - request_type=bigtable_instance_admin.DeleteAppProfileRequest, +def test_delete_logical_view_rest_bad_request( + request_type=bigtable_instance_admin.DeleteLogicalViewRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/appProfiles/sample3"} + request_init = {"name": "projects/sample1/instances/sample2/logicalViews/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_logical_view(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.DeleteLogicalViewRequest, + dict, + ], +) +def test_delete_logical_view_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2/logicalViews/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_logical_view(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_logical_view_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_delete_logical_view" + ) as pre: + pre.assert_not_called() + pb_message = bigtable_instance_admin.DeleteLogicalViewRequest.pb( + bigtable_instance_admin.DeleteLogicalViewRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = bigtable_instance_admin.DeleteLogicalViewRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_logical_view( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_create_materialized_view_rest_bad_request( + request_type=bigtable_instance_admin.CreateMaterializedViewRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/instances/sample2"} request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.delete_app_profile(request) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_materialized_view(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.CreateMaterializedViewRequest, + dict, + ], +) +def test_create_materialized_view_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/instances/sample2"} + request_init["materialized_view"] = { + "name": "name_value", + "query": "query_value", + "etag": "etag_value", + "deletion_protection": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = bigtable_instance_admin.CreateMaterializedViewRequest.meta.fields[ + "materialized_view" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + subfields_not_in_runtime = [] -@pytest.mark.parametrize( - "request_type", - [ - bigtable_instance_admin.DeleteAppProfileRequest, - dict, - ], -) -def test_delete_app_profile_rest_call_success(request_type): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["materialized_view"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/appProfiles/sample3"} + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["materialized_view"][field])): + del request_init["materialized_view"][field][i][subfield] + else: + del request_init["materialized_view"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_app_profile(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_materialized_view(request) # Establish that the response is the type that we expect. - assert response is None + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_app_profile_rest_interceptors(null_interceptor): +def test_create_materialized_view_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15953,11 +24133,20 @@ def test_delete_app_profile_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_delete_app_profile" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_create_materialized_view" + ) as post, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_create_materialized_view_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_create_materialized_view" ) as pre: pre.assert_not_called() - pb_message = bigtable_instance_admin.DeleteAppProfileRequest.pb( - bigtable_instance_admin.DeleteAppProfileRequest() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.CreateMaterializedViewRequest.pb( + bigtable_instance_admin.CreateMaterializedViewRequest() ) transcode.return_value = { "method": "post", @@ -15968,15 +24157,20 @@ def test_delete_app_profile_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - request = bigtable_instance_admin.DeleteAppProfileRequest() + request = bigtable_instance_admin.CreateMaterializedViewRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_app_profile( + client.create_materialized_view( request, metadata=[ ("key", "val"), @@ -15985,16 +24179,20 @@ def test_delete_app_profile_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.GetIamPolicyRequest, +def test_get_materialized_view_rest_bad_request( + request_type=bigtable_instance_admin.GetMaterializedViewRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/instances/sample2"} + request_init = { + "name": "projects/sample1/instances/sample2/materializedViews/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -16008,49 +24206,60 @@ def test_get_iam_policy_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.get_iam_policy(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_materialized_view(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.GetIamPolicyRequest, + bigtable_instance_admin.GetMaterializedViewRequest, dict, ], ) -def test_get_iam_policy_rest_call_success(request_type): +def test_get_materialized_view_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/instances/sample2"} + request_init = { + "name": "projects/sample1/instances/sample2/materializedViews/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy( - version=774, - etag=b"etag_blob", + return_value = instance.MaterializedView( + name="name_value", + query="query_value", + etag="etag_value", + deletion_protection=True, ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.MaterializedView.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_iam_policy(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_materialized_view(request) # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" + assert isinstance(response, instance.MaterializedView) + assert response.name == "name_value" + assert response.query == "query_value" + assert response.etag == "etag_value" + assert response.deletion_protection is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): +def test_get_materialized_view_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16064,13 +24273,19 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_get_iam_policy" + transports.BigtableInstanceAdminRestInterceptor, "post_get_materialized_view" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_get_iam_policy" + transports.BigtableInstanceAdminRestInterceptor, + "post_get_materialized_view_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_get_materialized_view" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.GetMaterializedViewRequest.pb( + bigtable_instance_admin.GetMaterializedViewRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16080,18 +24295,20 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.MaterializedView.to_json(instance.MaterializedView()) req.return_value.content = return_value - request = iam_policy_pb2.GetIamPolicyRequest() + request = bigtable_instance_admin.GetMaterializedViewRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() + post.return_value = instance.MaterializedView() + post_with_metadata.return_value = instance.MaterializedView(), metadata - client.get_iam_policy( + client.get_materialized_view( request, metadata=[ ("key", "val"), @@ -16101,16 +24318,17 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_set_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.SetIamPolicyRequest, +def test_list_materialized_views_rest_bad_request( + request_type=bigtable_instance_admin.ListMaterializedViewsRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/instances/sample2"} + request_init = {"parent": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -16124,49 +24342,54 @@ def test_set_iam_policy_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.set_iam_policy(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_materialized_views(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.SetIamPolicyRequest, + bigtable_instance_admin.ListMaterializedViewsRequest, dict, ], ) -def test_set_iam_policy_rest_call_success(request_type): +def test_list_materialized_views_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/instances/sample2"} + request_init = {"parent": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy( - version=774, - etag=b"etag_blob", + return_value = bigtable_instance_admin.ListMaterializedViewsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListMaterializedViewsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.set_iam_policy(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_materialized_views(request) # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" + assert isinstance(response, pagers.ListMaterializedViewsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): +def test_list_materialized_views_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16180,13 +24403,19 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_set_iam_policy" + transports.BigtableInstanceAdminRestInterceptor, "post_list_materialized_views" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_set_iam_policy" + transports.BigtableInstanceAdminRestInterceptor, + "post_list_materialized_views_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_list_materialized_views" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.ListMaterializedViewsRequest.pb( + bigtable_instance_admin.ListMaterializedViewsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16196,18 +24425,25 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = bigtable_instance_admin.ListMaterializedViewsResponse.to_json( + bigtable_instance_admin.ListMaterializedViewsResponse() + ) req.return_value.content = return_value - request = iam_policy_pb2.SetIamPolicyRequest() + request = bigtable_instance_admin.ListMaterializedViewsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() + post.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() + post_with_metadata.return_value = ( + bigtable_instance_admin.ListMaterializedViewsResponse(), + metadata, + ) - client.set_iam_policy( + client.list_materialized_views( request, metadata=[ ("key", "val"), @@ -16217,16 +24453,21 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_test_iam_permissions_rest_bad_request( - request_type=iam_policy_pb2.TestIamPermissionsRequest, +def test_update_materialized_view_rest_bad_request( + request_type=bigtable_instance_admin.UpdateMaterializedViewRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/instances/sample2"} + request_init = { + "materialized_view": { + "name": "projects/sample1/instances/sample2/materializedViews/sample3" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -16240,31 +24481,109 @@ def test_test_iam_permissions_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.test_iam_permissions(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_materialized_view(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, + bigtable_instance_admin.UpdateMaterializedViewRequest, dict, ], ) -def test_test_iam_permissions_rest_call_success(request_type): +def test_update_materialized_view_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/instances/sample2"} + request_init = { + "materialized_view": { + "name": "projects/sample1/instances/sample2/materializedViews/sample3" + } + } + request_init["materialized_view"] = { + "name": "projects/sample1/instances/sample2/materializedViews/sample3", + "query": "query_value", + "etag": "etag_value", + "deletion_protection": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = bigtable_instance_admin.UpdateMaterializedViewRequest.meta.fields[ + "materialized_view" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["materialized_view"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["materialized_view"][field])): + del request_init["materialized_view"][field][i][subfield] + else: + del request_init["materialized_view"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -16272,15 +24591,15 @@ def test_test_iam_permissions_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.test_iam_permissions(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_materialized_view(request) # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): +def test_update_materialized_view_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16294,13 +24613,21 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_test_iam_permissions" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_update_materialized_view" ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_test_iam_permissions" + transports.BigtableInstanceAdminRestInterceptor, + "post_update_materialized_view_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_update_materialized_view" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.UpdateMaterializedViewRequest.pb( + bigtable_instance_admin.UpdateMaterializedViewRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16310,20 +24637,20 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = json_format.MessageToJson( - iam_policy_pb2.TestIamPermissionsResponse() - ) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = iam_policy_pb2.TestIamPermissionsRequest() + request = bigtable_instance_admin.UpdateMaterializedViewRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.test_iam_permissions( + client.update_materialized_view( request, metadata=[ ("key", "val"), @@ -16333,16 +24660,19 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() -def test_list_hot_tablets_rest_bad_request( - request_type=bigtable_instance_admin.ListHotTabletsRequest, +def test_delete_materialized_view_rest_bad_request( + request_type=bigtable_instance_admin.DeleteMaterializedViewRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/instances/sample2/clusters/sample3"} + request_init = { + "name": "projects/sample1/instances/sample2/materializedViews/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -16356,50 +24686,48 @@ def test_list_hot_tablets_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.list_hot_tablets(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_materialized_view(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListHotTabletsRequest, + bigtable_instance_admin.DeleteMaterializedViewRequest, dict, ], ) -def test_list_hot_tablets_rest_call_success(request_type): +def test_delete_materialized_view_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/instances/sample2/clusters/sample3"} + request_init = { + "name": "projects/sample1/instances/sample2/materializedViews/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListHotTabletsResponse( - next_page_token="next_page_token_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListHotTabletsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_hot_tablets(request) + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_materialized_view(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListHotTabletsPager) - assert response.next_page_token == "next_page_token_value" + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_hot_tablets_rest_interceptors(null_interceptor): +def test_delete_materialized_view_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16413,14 +24741,11 @@ def test_list_hot_tablets_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_list_hot_tablets" - ) as post, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_list_hot_tablets" + transports.BigtableInstanceAdminRestInterceptor, "pre_delete_materialized_view" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = bigtable_instance_admin.ListHotTabletsRequest.pb( - bigtable_instance_admin.ListHotTabletsRequest() + pb_message = bigtable_instance_admin.DeleteMaterializedViewRequest.pb( + bigtable_instance_admin.DeleteMaterializedViewRequest() ) transcode.return_value = { "method": "post", @@ -16431,20 +24756,16 @@ def test_list_hot_tablets_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = bigtable_instance_admin.ListHotTabletsResponse.to_json( - bigtable_instance_admin.ListHotTabletsResponse() - ) - req.return_value.content = return_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - request = bigtable_instance_admin.ListHotTabletsRequest() + request = bigtable_instance_admin.DeleteMaterializedViewRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = bigtable_instance_admin.ListHotTabletsResponse() - client.list_hot_tablets( + client.delete_materialized_view( request, metadata=[ ("key", "val"), @@ -16453,7 +24774,6 @@ def test_list_hot_tablets_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() def test_initialize_client_w_rest(): @@ -16897,6 +25217,224 @@ def test_list_hot_tablets_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_logical_view_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: + client.create_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_logical_view_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + client.get_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_logical_views_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + client.list_logical_views(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListLogicalViewsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_logical_view_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_logical_view), "__call__" + ) as call: + client.update_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_logical_view_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_logical_view), "__call__" + ) as call: + client.delete_logical_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteLogicalViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_materialized_view_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__call__" + ) as call: + client.create_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateMaterializedViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_materialized_view_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + client.get_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetMaterializedViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_materialized_views_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + client.list_materialized_views(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListMaterializedViewsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_materialized_view_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_materialized_view), "__call__" + ) as call: + client.update_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateMaterializedViewRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_materialized_view_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_materialized_view), "__call__" + ) as call: + client.delete_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteMaterializedViewRequest() + + assert args[0] == request_msg + + def test_bigtable_instance_admin_rest_lro_client(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16968,6 +25506,16 @@ def test_bigtable_instance_admin_base_transport(): "set_iam_policy", "test_iam_permissions", "list_hot_tablets", + "create_logical_view", + "get_logical_view", + "list_logical_views", + "update_logical_view", + "delete_logical_view", + "create_materialized_view", + "get_materialized_view", + "list_materialized_views", + "update_materialized_view", + "delete_materialized_view", ) for method in methods: with pytest.raises(NotImplementedError): @@ -17330,6 +25878,36 @@ def test_bigtable_instance_admin_client_transport_session_collision(transport_na session1 = client1.transport.list_hot_tablets._session session2 = client2.transport.list_hot_tablets._session assert session1 != session2 + session1 = client1.transport.create_logical_view._session + session2 = client2.transport.create_logical_view._session + assert session1 != session2 + session1 = client1.transport.get_logical_view._session + session2 = client2.transport.get_logical_view._session + assert session1 != session2 + session1 = client1.transport.list_logical_views._session + session2 = client2.transport.list_logical_views._session + assert session1 != session2 + session1 = client1.transport.update_logical_view._session + session2 = client2.transport.update_logical_view._session + assert session1 != session2 + session1 = client1.transport.delete_logical_view._session + session2 = client2.transport.delete_logical_view._session + assert session1 != session2 + session1 = client1.transport.create_materialized_view._session + session2 = client2.transport.create_materialized_view._session + assert session1 != session2 + session1 = client1.transport.get_materialized_view._session + session2 = client2.transport.get_materialized_view._session + assert session1 != session2 + session1 = client1.transport.list_materialized_views._session + session2 = client2.transport.list_materialized_views._session + assert session1 != session2 + session1 = client1.transport.update_materialized_view._session + session2 = client2.transport.update_materialized_view._session + assert session1 != session2 + session1 = client1.transport.delete_materialized_view._session + session2 = client2.transport.delete_materialized_view._session + assert session1 != session2 def test_bigtable_instance_admin_grpc_transport_channel(): @@ -17633,6 +26211,64 @@ def test_parse_instance_path(): assert expected == actual +def test_logical_view_path(): + project = "winkle" + instance = "nautilus" + logical_view = "scallop" + expected = ( + "projects/{project}/instances/{instance}/logicalViews/{logical_view}".format( + project=project, + instance=instance, + logical_view=logical_view, + ) + ) + actual = BigtableInstanceAdminClient.logical_view_path( + project, instance, logical_view + ) + assert expected == actual + + +def test_parse_logical_view_path(): + expected = { + "project": "abalone", + "instance": "squid", + "logical_view": "clam", + } + path = BigtableInstanceAdminClient.logical_view_path(**expected) + + # Check that the path construction is reversible. + actual = BigtableInstanceAdminClient.parse_logical_view_path(path) + assert expected == actual + + +def test_materialized_view_path(): + project = "whelk" + instance = "octopus" + materialized_view = "oyster" + expected = "projects/{project}/instances/{instance}/materializedViews/{materialized_view}".format( + project=project, + instance=instance, + materialized_view=materialized_view, + ) + actual = BigtableInstanceAdminClient.materialized_view_path( + project, instance, materialized_view + ) + assert expected == actual + + +def test_parse_materialized_view_path(): + expected = { + "project": "nudibranch", + "instance": "cuttlefish", + "materialized_view": "mussel", + } + path = BigtableInstanceAdminClient.materialized_view_path(**expected) + + # Check that the path construction is reversible. + actual = BigtableInstanceAdminClient.parse_materialized_view_path(path) + assert expected == actual + + def test_table_path(): project = "winkle" instance = "nautilus" diff --git a/tests/unit/gapic/bigtable_admin_v2/test_bigtable_table_admin.py b/tests/unit/gapic/bigtable_admin_v2/test_bigtable_table_admin.py index 53788921f..21d2720d7 100644 --- a/tests/unit/gapic/bigtable_admin_v2/test_bigtable_table_admin.py +++ b/tests/unit/gapic/bigtable_admin_v2/test_bigtable_table_admin.py @@ -83,6 +83,14 @@ import google.auth +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + async def mock_async_gen(data, chunk_size=1): for i in range(0, len(data)): # pragma: NO COVER chunk = data[i : i + chunk_size] @@ -353,6 +361,49 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = BigtableTableAdminClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = BigtableTableAdminClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + @pytest.mark.parametrize( "client_class,transport_name", [ @@ -12093,6 +12144,7 @@ def test_create_table_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_table(request) @@ -12149,6 +12201,7 @@ def test_create_table_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_table(**mock_args) @@ -12296,6 +12349,7 @@ def test_create_table_from_snapshot_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_table_from_snapshot(request) @@ -12350,6 +12404,7 @@ def test_create_table_from_snapshot_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_table_from_snapshot(**mock_args) @@ -12491,6 +12546,7 @@ def test_list_tables_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_tables(request) @@ -12545,6 +12601,7 @@ def test_list_tables_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_tables(**mock_args) @@ -12740,6 +12797,7 @@ def test_get_table_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_table(request) @@ -12785,6 +12843,7 @@ def test_get_table_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_table(**mock_args) @@ -12878,7 +12937,12 @@ def test_update_table_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).update_table._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set( + ( + "ignore_warnings", + "update_mask", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -12914,6 +12978,7 @@ def test_update_table_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_table(request) @@ -12929,7 +12994,12 @@ def test_update_table_rest_unset_required_fields(): unset_fields = transport.update_table._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("updateMask",)) + set( + ( + "ignoreWarnings", + "updateMask", + ) + ) & set( ( "table", @@ -12968,6 +13038,7 @@ def test_update_table_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.update_table(**mock_args) @@ -13097,6 +13168,7 @@ def test_delete_table_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_table(request) @@ -13140,6 +13212,7 @@ def test_delete_table_rest_flattened(): json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_table(**mock_args) @@ -13272,6 +13345,7 @@ def test_undelete_table_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.undelete_table(request) @@ -13315,6 +13389,7 @@ def test_undelete_table_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.undelete_table(**mock_args) @@ -13462,6 +13537,7 @@ def test_create_authorized_view_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_authorized_view(request) @@ -13522,6 +13598,7 @@ def test_create_authorized_view_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_authorized_view(**mock_args) @@ -13670,6 +13747,7 @@ def test_list_authorized_views_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_authorized_views(request) @@ -13724,6 +13802,7 @@ def test_list_authorized_views_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_authorized_views(**mock_args) @@ -13925,6 +14004,7 @@ def test_get_authorized_view_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_authorized_view(request) @@ -13972,6 +14052,7 @@ def test_get_authorized_view_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_authorized_view(**mock_args) @@ -14112,6 +14193,7 @@ def test_update_authorized_view_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_authorized_view(request) @@ -14168,6 +14250,7 @@ def test_update_authorized_view_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.update_authorized_view(**mock_args) @@ -14304,6 +14387,7 @@ def test_delete_authorized_view_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_authorized_view(request) @@ -14349,6 +14433,7 @@ def test_delete_authorized_view_rest_flattened(): json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_authorized_view(**mock_args) @@ -14486,6 +14571,7 @@ def test_modify_column_families_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.modify_column_families(request) @@ -14544,6 +14630,7 @@ def test_modify_column_families_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.modify_column_families(**mock_args) @@ -14678,6 +14765,7 @@ def test_drop_row_range_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.drop_row_range(request) @@ -14805,6 +14893,7 @@ def test_generate_consistency_token_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_consistency_token(request) @@ -14852,6 +14941,7 @@ def test_generate_consistency_token_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.generate_consistency_token(**mock_args) @@ -14992,6 +15082,7 @@ def test_check_consistency_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.check_consistency(request) @@ -15046,6 +15137,7 @@ def test_check_consistency_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.check_consistency(**mock_args) @@ -15188,6 +15280,7 @@ def test_snapshot_table_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.snapshot_table(request) @@ -15243,6 +15336,7 @@ def test_snapshot_table_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.snapshot_table(**mock_args) @@ -15377,6 +15471,7 @@ def test_get_snapshot_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_snapshot(request) @@ -15424,6 +15519,7 @@ def test_get_snapshot_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_snapshot(**mock_args) @@ -15562,6 +15658,7 @@ def test_list_snapshots_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_snapshots(request) @@ -15617,6 +15714,7 @@ def test_list_snapshots_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_snapshots(**mock_args) @@ -15810,6 +15908,7 @@ def test_delete_snapshot_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_snapshot(request) @@ -15855,6 +15954,7 @@ def test_delete_snapshot_rest_flattened(): json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_snapshot(**mock_args) @@ -15997,6 +16097,7 @@ def test_create_backup_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_backup(request) @@ -16059,6 +16160,7 @@ def test_create_backup_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_backup(**mock_args) @@ -16192,6 +16294,7 @@ def test_get_backup_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_backup(request) @@ -16239,6 +16342,7 @@ def test_get_backup_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_backup(**mock_args) @@ -16368,6 +16472,7 @@ def test_update_backup_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_backup(request) @@ -16426,6 +16531,7 @@ def test_update_backup_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.update_backup(**mock_args) @@ -16555,6 +16661,7 @@ def test_delete_backup_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_backup(request) @@ -16600,6 +16707,7 @@ def test_delete_backup_rest_flattened(): json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_backup(**mock_args) @@ -16740,6 +16848,7 @@ def test_list_backups_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_backups(request) @@ -16797,6 +16906,7 @@ def test_list_backups_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_backups(**mock_args) @@ -16999,6 +17109,7 @@ def test_restore_table_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.restore_table(request) @@ -17136,6 +17247,7 @@ def test_copy_backup_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.copy_backup(request) @@ -17194,6 +17306,7 @@ def test_copy_backup_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.copy_backup(**mock_args) @@ -17327,6 +17440,7 @@ def test_get_iam_policy_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_iam_policy(request) @@ -17372,6 +17486,7 @@ def test_get_iam_policy_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_iam_policy(**mock_args) @@ -17502,6 +17617,7 @@ def test_set_iam_policy_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.set_iam_policy(request) @@ -17555,6 +17671,7 @@ def test_set_iam_policy_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.set_iam_policy(**mock_args) @@ -17693,6 +17810,7 @@ def test_test_iam_permissions_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.test_iam_permissions(request) @@ -17747,6 +17865,7 @@ def test_test_iam_permissions_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.test_iam_permissions(**mock_args) @@ -19390,6 +19509,7 @@ def test_create_table_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_table(request) @@ -19427,6 +19547,7 @@ def test_create_table_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_table(request) # Establish that the response is the type that we expect. @@ -19453,10 +19574,13 @@ def test_create_table_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_create_table" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_create_table_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_create_table" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.CreateTableRequest.pb( bigtable_table_admin.CreateTableRequest() ) @@ -19469,6 +19593,7 @@ def test_create_table_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = gba_table.Table.to_json(gba_table.Table()) req.return_value.content = return_value @@ -19479,6 +19604,7 @@ def test_create_table_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = gba_table.Table() + post_with_metadata.return_value = gba_table.Table(), metadata client.create_table( request, @@ -19490,6 +19616,7 @@ def test_create_table_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_create_table_from_snapshot_rest_bad_request( @@ -19513,6 +19640,7 @@ def test_create_table_from_snapshot_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_table_from_snapshot(request) @@ -19543,6 +19671,7 @@ def test_create_table_from_snapshot_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_table_from_snapshot(request) # Establish that the response is the type that we expect. @@ -19568,10 +19697,14 @@ def test_create_table_from_snapshot_rest_interceptors(null_interceptor): ), mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_create_table_from_snapshot" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_create_table_from_snapshot_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_create_table_from_snapshot" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.CreateTableFromSnapshotRequest.pb( bigtable_table_admin.CreateTableFromSnapshotRequest() ) @@ -19584,6 +19717,7 @@ def test_create_table_from_snapshot_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -19594,6 +19728,7 @@ def test_create_table_from_snapshot_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata client.create_table_from_snapshot( request, @@ -19605,6 +19740,7 @@ def test_create_table_from_snapshot_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_list_tables_rest_bad_request( @@ -19628,6 +19764,7 @@ def test_list_tables_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_tables(request) @@ -19663,6 +19800,7 @@ def test_list_tables_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_tables(request) # Establish that the response is the type that we expect. @@ -19687,10 +19825,13 @@ def test_list_tables_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_list_tables" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_list_tables_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_list_tables" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.ListTablesRequest.pb( bigtable_table_admin.ListTablesRequest() ) @@ -19703,6 +19844,7 @@ def test_list_tables_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable_table_admin.ListTablesResponse.to_json( bigtable_table_admin.ListTablesResponse() ) @@ -19715,6 +19857,10 @@ def test_list_tables_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable_table_admin.ListTablesResponse() + post_with_metadata.return_value = ( + bigtable_table_admin.ListTablesResponse(), + metadata, + ) client.list_tables( request, @@ -19726,6 +19872,7 @@ def test_list_tables_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_get_table_rest_bad_request(request_type=bigtable_table_admin.GetTableRequest): @@ -19747,6 +19894,7 @@ def test_get_table_rest_bad_request(request_type=bigtable_table_admin.GetTableRe response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_table(request) @@ -19784,6 +19932,7 @@ def test_get_table_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_table(request) # Establish that the response is the type that we expect. @@ -19810,10 +19959,13 @@ def test_get_table_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_get_table" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_get_table_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_get_table" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.GetTableRequest.pb( bigtable_table_admin.GetTableRequest() ) @@ -19826,6 +19978,7 @@ def test_get_table_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = table.Table.to_json(table.Table()) req.return_value.content = return_value @@ -19836,6 +19989,7 @@ def test_get_table_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = table.Table() + post_with_metadata.return_value = table.Table(), metadata client.get_table( request, @@ -19847,6 +20001,7 @@ def test_get_table_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_update_table_rest_bad_request( @@ -19872,6 +20027,7 @@ def test_update_table_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.update_table(request) @@ -19909,6 +20065,44 @@ def test_update_table_rest_call_success(request_type): "change_stream_config": {"retention_period": {"seconds": 751, "nanos": 543}}, "deletion_protection": True, "automated_backup_policy": {"retention_period": {}, "frequency": {}}, + "row_key_schema": { + "fields": [ + { + "field_name": "field_name_value", + "type_": { + "bytes_type": {"encoding": {"raw": {}}}, + "string_type": {"encoding": {"utf8_raw": {}, "utf8_bytes": {}}}, + "int64_type": { + "encoding": { + "big_endian_bytes": {"bytes_type": {}}, + "ordered_code_bytes": {}, + } + }, + "float32_type": {}, + "float64_type": {}, + "bool_type": {}, + "timestamp_type": {"encoding": {"unix_micros_int64": {}}}, + "date_type": {}, + "aggregate_type": { + "input_type": {}, + "state_type": {}, + "sum": {}, + "hllpp_unique_count": {}, + "max_": {}, + "min_": {}, + }, + "struct_type": {}, + "array_type": {"element_type": {}}, + "map_type": {"key_type": {}, "value_type": {}}, + }, + } + ], + "encoding": { + "singleton": {}, + "delimited_bytes": {"delimiter": b"delimiter_blob"}, + "ordered_code_bytes": {}, + }, + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -19990,6 +20184,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_table(request) # Establish that the response is the type that we expect. @@ -20015,10 +20210,13 @@ def test_update_table_rest_interceptors(null_interceptor): ), mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_update_table" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_update_table_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_update_table" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.UpdateTableRequest.pb( bigtable_table_admin.UpdateTableRequest() ) @@ -20031,6 +20229,7 @@ def test_update_table_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -20041,6 +20240,7 @@ def test_update_table_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata client.update_table( request, @@ -20052,6 +20252,7 @@ def test_update_table_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_delete_table_rest_bad_request( @@ -20075,6 +20276,7 @@ def test_delete_table_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_table(request) @@ -20105,6 +20307,7 @@ def test_delete_table_rest_call_success(request_type): json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_table(request) # Establish that the response is the type that we expect. @@ -20141,6 +20344,7 @@ def test_delete_table_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = bigtable_table_admin.DeleteTableRequest() metadata = [ @@ -20181,6 +20385,7 @@ def test_undelete_table_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.undelete_table(request) @@ -20211,6 +20416,7 @@ def test_undelete_table_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.undelete_table(request) # Establish that the response is the type that we expect. @@ -20236,10 +20442,14 @@ def test_undelete_table_rest_interceptors(null_interceptor): ), mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_undelete_table" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_undelete_table_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_undelete_table" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.UndeleteTableRequest.pb( bigtable_table_admin.UndeleteTableRequest() ) @@ -20252,6 +20462,7 @@ def test_undelete_table_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -20262,6 +20473,7 @@ def test_undelete_table_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata client.undelete_table( request, @@ -20273,6 +20485,7 @@ def test_undelete_table_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_create_authorized_view_rest_bad_request( @@ -20296,6 +20509,7 @@ def test_create_authorized_view_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_authorized_view(request) @@ -20404,6 +20618,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_authorized_view(request) # Establish that the response is the type that we expect. @@ -20429,10 +20644,14 @@ def test_create_authorized_view_rest_interceptors(null_interceptor): ), mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_create_authorized_view" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_create_authorized_view_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_create_authorized_view" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.CreateAuthorizedViewRequest.pb( bigtable_table_admin.CreateAuthorizedViewRequest() ) @@ -20445,6 +20664,7 @@ def test_create_authorized_view_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -20455,6 +20675,7 @@ def test_create_authorized_view_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata client.create_authorized_view( request, @@ -20466,6 +20687,7 @@ def test_create_authorized_view_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_list_authorized_views_rest_bad_request( @@ -20489,6 +20711,7 @@ def test_list_authorized_views_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_authorized_views(request) @@ -20524,6 +20747,7 @@ def test_list_authorized_views_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_authorized_views(request) # Establish that the response is the type that we expect. @@ -20548,10 +20772,14 @@ def test_list_authorized_views_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_list_authorized_views" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_list_authorized_views_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_list_authorized_views" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.ListAuthorizedViewsRequest.pb( bigtable_table_admin.ListAuthorizedViewsRequest() ) @@ -20564,6 +20792,7 @@ def test_list_authorized_views_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable_table_admin.ListAuthorizedViewsResponse.to_json( bigtable_table_admin.ListAuthorizedViewsResponse() ) @@ -20576,6 +20805,10 @@ def test_list_authorized_views_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable_table_admin.ListAuthorizedViewsResponse() + post_with_metadata.return_value = ( + bigtable_table_admin.ListAuthorizedViewsResponse(), + metadata, + ) client.list_authorized_views( request, @@ -20587,6 +20820,7 @@ def test_list_authorized_views_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_get_authorized_view_rest_bad_request( @@ -20612,6 +20846,7 @@ def test_get_authorized_view_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_authorized_view(request) @@ -20651,6 +20886,7 @@ def test_get_authorized_view_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_authorized_view(request) # Establish that the response is the type that we expect. @@ -20677,10 +20913,14 @@ def test_get_authorized_view_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_get_authorized_view" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_get_authorized_view_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_get_authorized_view" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.GetAuthorizedViewRequest.pb( bigtable_table_admin.GetAuthorizedViewRequest() ) @@ -20693,6 +20933,7 @@ def test_get_authorized_view_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = table.AuthorizedView.to_json(table.AuthorizedView()) req.return_value.content = return_value @@ -20703,6 +20944,7 @@ def test_get_authorized_view_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = table.AuthorizedView() + post_with_metadata.return_value = table.AuthorizedView(), metadata client.get_authorized_view( request, @@ -20714,6 +20956,7 @@ def test_get_authorized_view_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_update_authorized_view_rest_bad_request( @@ -20741,6 +20984,7 @@ def test_update_authorized_view_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.update_authorized_view(request) @@ -20853,6 +21097,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_authorized_view(request) # Establish that the response is the type that we expect. @@ -20878,10 +21123,14 @@ def test_update_authorized_view_rest_interceptors(null_interceptor): ), mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_update_authorized_view" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_update_authorized_view_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_update_authorized_view" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.UpdateAuthorizedViewRequest.pb( bigtable_table_admin.UpdateAuthorizedViewRequest() ) @@ -20894,6 +21143,7 @@ def test_update_authorized_view_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -20904,6 +21154,7 @@ def test_update_authorized_view_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata client.update_authorized_view( request, @@ -20915,6 +21166,7 @@ def test_update_authorized_view_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_delete_authorized_view_rest_bad_request( @@ -20940,6 +21192,7 @@ def test_delete_authorized_view_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_authorized_view(request) @@ -20972,6 +21225,7 @@ def test_delete_authorized_view_rest_call_success(request_type): json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_authorized_view(request) # Establish that the response is the type that we expect. @@ -21008,6 +21262,7 @@ def test_delete_authorized_view_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = bigtable_table_admin.DeleteAuthorizedViewRequest() metadata = [ @@ -21048,6 +21303,7 @@ def test_modify_column_families_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.modify_column_families(request) @@ -21085,6 +21341,7 @@ def test_modify_column_families_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.modify_column_families(request) # Establish that the response is the type that we expect. @@ -21111,10 +21368,14 @@ def test_modify_column_families_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_modify_column_families" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_modify_column_families_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_modify_column_families" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.ModifyColumnFamiliesRequest.pb( bigtable_table_admin.ModifyColumnFamiliesRequest() ) @@ -21127,6 +21388,7 @@ def test_modify_column_families_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = table.Table.to_json(table.Table()) req.return_value.content = return_value @@ -21137,6 +21399,7 @@ def test_modify_column_families_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = table.Table() + post_with_metadata.return_value = table.Table(), metadata client.modify_column_families( request, @@ -21148,6 +21411,7 @@ def test_modify_column_families_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_drop_row_range_rest_bad_request( @@ -21171,6 +21435,7 @@ def test_drop_row_range_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.drop_row_range(request) @@ -21201,6 +21466,7 @@ def test_drop_row_range_rest_call_success(request_type): json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.drop_row_range(request) # Establish that the response is the type that we expect. @@ -21237,6 +21503,7 @@ def test_drop_row_range_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = bigtable_table_admin.DropRowRangeRequest() metadata = [ @@ -21277,6 +21544,7 @@ def test_generate_consistency_token_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.generate_consistency_token(request) @@ -21314,6 +21582,7 @@ def test_generate_consistency_token_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_consistency_token(request) # Establish that the response is the type that we expect. @@ -21338,10 +21607,14 @@ def test_generate_consistency_token_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_generate_consistency_token" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_generate_consistency_token_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_generate_consistency_token" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.GenerateConsistencyTokenRequest.pb( bigtable_table_admin.GenerateConsistencyTokenRequest() ) @@ -21354,6 +21627,7 @@ def test_generate_consistency_token_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable_table_admin.GenerateConsistencyTokenResponse.to_json( bigtable_table_admin.GenerateConsistencyTokenResponse() ) @@ -21366,6 +21640,10 @@ def test_generate_consistency_token_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable_table_admin.GenerateConsistencyTokenResponse() + post_with_metadata.return_value = ( + bigtable_table_admin.GenerateConsistencyTokenResponse(), + metadata, + ) client.generate_consistency_token( request, @@ -21377,6 +21655,7 @@ def test_generate_consistency_token_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_check_consistency_rest_bad_request( @@ -21400,6 +21679,7 @@ def test_check_consistency_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.check_consistency(request) @@ -21435,6 +21715,7 @@ def test_check_consistency_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.check_consistency(request) # Establish that the response is the type that we expect. @@ -21459,10 +21740,14 @@ def test_check_consistency_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_check_consistency" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_check_consistency_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_check_consistency" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.CheckConsistencyRequest.pb( bigtable_table_admin.CheckConsistencyRequest() ) @@ -21475,6 +21760,7 @@ def test_check_consistency_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable_table_admin.CheckConsistencyResponse.to_json( bigtable_table_admin.CheckConsistencyResponse() ) @@ -21487,6 +21773,10 @@ def test_check_consistency_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable_table_admin.CheckConsistencyResponse() + post_with_metadata.return_value = ( + bigtable_table_admin.CheckConsistencyResponse(), + metadata, + ) client.check_consistency( request, @@ -21498,6 +21788,7 @@ def test_check_consistency_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_snapshot_table_rest_bad_request( @@ -21521,6 +21812,7 @@ def test_snapshot_table_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.snapshot_table(request) @@ -21551,6 +21843,7 @@ def test_snapshot_table_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.snapshot_table(request) # Establish that the response is the type that we expect. @@ -21576,10 +21869,14 @@ def test_snapshot_table_rest_interceptors(null_interceptor): ), mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_snapshot_table" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_snapshot_table_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_snapshot_table" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.SnapshotTableRequest.pb( bigtable_table_admin.SnapshotTableRequest() ) @@ -21592,6 +21889,7 @@ def test_snapshot_table_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -21602,6 +21900,7 @@ def test_snapshot_table_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata client.snapshot_table( request, @@ -21613,6 +21912,7 @@ def test_snapshot_table_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_get_snapshot_rest_bad_request( @@ -21638,6 +21938,7 @@ def test_get_snapshot_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_snapshot(request) @@ -21678,6 +21979,7 @@ def test_get_snapshot_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_snapshot(request) # Establish that the response is the type that we expect. @@ -21705,10 +22007,13 @@ def test_get_snapshot_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_get_snapshot" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_get_snapshot_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_get_snapshot" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.GetSnapshotRequest.pb( bigtable_table_admin.GetSnapshotRequest() ) @@ -21721,6 +22026,7 @@ def test_get_snapshot_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = table.Snapshot.to_json(table.Snapshot()) req.return_value.content = return_value @@ -21731,6 +22037,7 @@ def test_get_snapshot_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = table.Snapshot() + post_with_metadata.return_value = table.Snapshot(), metadata client.get_snapshot( request, @@ -21742,6 +22049,7 @@ def test_get_snapshot_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_list_snapshots_rest_bad_request( @@ -21765,6 +22073,7 @@ def test_list_snapshots_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_snapshots(request) @@ -21800,6 +22109,7 @@ def test_list_snapshots_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_snapshots(request) # Establish that the response is the type that we expect. @@ -21824,10 +22134,14 @@ def test_list_snapshots_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_list_snapshots" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_list_snapshots_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_list_snapshots" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.ListSnapshotsRequest.pb( bigtable_table_admin.ListSnapshotsRequest() ) @@ -21840,6 +22154,7 @@ def test_list_snapshots_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable_table_admin.ListSnapshotsResponse.to_json( bigtable_table_admin.ListSnapshotsResponse() ) @@ -21852,6 +22167,10 @@ def test_list_snapshots_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable_table_admin.ListSnapshotsResponse() + post_with_metadata.return_value = ( + bigtable_table_admin.ListSnapshotsResponse(), + metadata, + ) client.list_snapshots( request, @@ -21863,6 +22182,7 @@ def test_list_snapshots_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_delete_snapshot_rest_bad_request( @@ -21888,6 +22208,7 @@ def test_delete_snapshot_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_snapshot(request) @@ -21920,6 +22241,7 @@ def test_delete_snapshot_rest_call_success(request_type): json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_snapshot(request) # Establish that the response is the type that we expect. @@ -21956,6 +22278,7 @@ def test_delete_snapshot_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = bigtable_table_admin.DeleteSnapshotRequest() metadata = [ @@ -21996,6 +22319,7 @@ def test_create_backup_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_backup(request) @@ -22119,6 +22443,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_backup(request) # Establish that the response is the type that we expect. @@ -22144,10 +22469,13 @@ def test_create_backup_rest_interceptors(null_interceptor): ), mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_create_backup" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_create_backup_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_create_backup" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.CreateBackupRequest.pb( bigtable_table_admin.CreateBackupRequest() ) @@ -22160,6 +22488,7 @@ def test_create_backup_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -22170,6 +22499,7 @@ def test_create_backup_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata client.create_backup( request, @@ -22181,6 +22511,7 @@ def test_create_backup_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_get_backup_rest_bad_request( @@ -22206,6 +22537,7 @@ def test_get_backup_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_backup(request) @@ -22248,6 +22580,7 @@ def test_get_backup_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_backup(request) # Establish that the response is the type that we expect. @@ -22277,10 +22610,13 @@ def test_get_backup_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_get_backup" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_get_backup_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_get_backup" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.GetBackupRequest.pb( bigtable_table_admin.GetBackupRequest() ) @@ -22293,6 +22629,7 @@ def test_get_backup_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = table.Backup.to_json(table.Backup()) req.return_value.content = return_value @@ -22303,6 +22640,7 @@ def test_get_backup_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = table.Backup() + post_with_metadata.return_value = table.Backup(), metadata client.get_backup( request, @@ -22314,6 +22652,7 @@ def test_get_backup_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_update_backup_rest_bad_request( @@ -22341,6 +22680,7 @@ def test_update_backup_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.update_backup(request) @@ -22478,6 +22818,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_backup(request) # Establish that the response is the type that we expect. @@ -22507,10 +22848,13 @@ def test_update_backup_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_update_backup" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_update_backup_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_update_backup" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.UpdateBackupRequest.pb( bigtable_table_admin.UpdateBackupRequest() ) @@ -22523,6 +22867,7 @@ def test_update_backup_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = table.Backup.to_json(table.Backup()) req.return_value.content = return_value @@ -22533,6 +22878,7 @@ def test_update_backup_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = table.Backup() + post_with_metadata.return_value = table.Backup(), metadata client.update_backup( request, @@ -22544,6 +22890,7 @@ def test_update_backup_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_delete_backup_rest_bad_request( @@ -22569,6 +22916,7 @@ def test_delete_backup_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_backup(request) @@ -22601,6 +22949,7 @@ def test_delete_backup_rest_call_success(request_type): json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_backup(request) # Establish that the response is the type that we expect. @@ -22637,6 +22986,7 @@ def test_delete_backup_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = bigtable_table_admin.DeleteBackupRequest() metadata = [ @@ -22677,6 +23027,7 @@ def test_list_backups_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_backups(request) @@ -22712,6 +23063,7 @@ def test_list_backups_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_backups(request) # Establish that the response is the type that we expect. @@ -22736,10 +23088,13 @@ def test_list_backups_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_list_backups" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_list_backups_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_list_backups" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.ListBackupsRequest.pb( bigtable_table_admin.ListBackupsRequest() ) @@ -22752,6 +23107,7 @@ def test_list_backups_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable_table_admin.ListBackupsResponse.to_json( bigtable_table_admin.ListBackupsResponse() ) @@ -22764,6 +23120,10 @@ def test_list_backups_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable_table_admin.ListBackupsResponse() + post_with_metadata.return_value = ( + bigtable_table_admin.ListBackupsResponse(), + metadata, + ) client.list_backups( request, @@ -22775,6 +23135,7 @@ def test_list_backups_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_restore_table_rest_bad_request( @@ -22798,6 +23159,7 @@ def test_restore_table_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.restore_table(request) @@ -22828,6 +23190,7 @@ def test_restore_table_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.restore_table(request) # Establish that the response is the type that we expect. @@ -22853,10 +23216,13 @@ def test_restore_table_rest_interceptors(null_interceptor): ), mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_restore_table" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_restore_table_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_restore_table" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.RestoreTableRequest.pb( bigtable_table_admin.RestoreTableRequest() ) @@ -22869,6 +23235,7 @@ def test_restore_table_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -22879,6 +23246,7 @@ def test_restore_table_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata client.restore_table( request, @@ -22890,6 +23258,7 @@ def test_restore_table_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_copy_backup_rest_bad_request( @@ -22913,6 +23282,7 @@ def test_copy_backup_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.copy_backup(request) @@ -22943,6 +23313,7 @@ def test_copy_backup_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.copy_backup(request) # Establish that the response is the type that we expect. @@ -22968,10 +23339,13 @@ def test_copy_backup_rest_interceptors(null_interceptor): ), mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_copy_backup" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, "post_copy_backup_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_copy_backup" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable_table_admin.CopyBackupRequest.pb( bigtable_table_admin.CopyBackupRequest() ) @@ -22984,6 +23358,7 @@ def test_copy_backup_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -22994,6 +23369,7 @@ def test_copy_backup_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata client.copy_backup( request, @@ -23005,6 +23381,7 @@ def test_copy_backup_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_get_iam_policy_rest_bad_request( @@ -23028,6 +23405,7 @@ def test_get_iam_policy_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_iam_policy(request) @@ -23061,6 +23439,7 @@ def test_get_iam_policy_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_iam_policy(request) # Establish that the response is the type that we expect. @@ -23086,10 +23465,14 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_get_iam_policy" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_get_iam_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_get_iam_policy" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = iam_policy_pb2.GetIamPolicyRequest() transcode.return_value = { "method": "post", @@ -23100,6 +23483,7 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(policy_pb2.Policy()) req.return_value.content = return_value @@ -23110,6 +23494,7 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata client.get_iam_policy( request, @@ -23121,6 +23506,7 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_set_iam_policy_rest_bad_request( @@ -23144,6 +23530,7 @@ def test_set_iam_policy_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.set_iam_policy(request) @@ -23177,6 +23564,7 @@ def test_set_iam_policy_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.set_iam_policy(request) # Establish that the response is the type that we expect. @@ -23202,10 +23590,14 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_set_iam_policy" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_set_iam_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_set_iam_policy" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = iam_policy_pb2.SetIamPolicyRequest() transcode.return_value = { "method": "post", @@ -23216,6 +23608,7 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(policy_pb2.Policy()) req.return_value.content = return_value @@ -23226,6 +23619,7 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata client.set_iam_policy( request, @@ -23237,6 +23631,7 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_test_iam_permissions_rest_bad_request( @@ -23260,6 +23655,7 @@ def test_test_iam_permissions_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.test_iam_permissions(request) @@ -23292,6 +23688,7 @@ def test_test_iam_permissions_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.test_iam_permissions(request) # Establish that the response is the type that we expect. @@ -23316,10 +23713,14 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "post_test_iam_permissions" ) as post, mock.patch.object( + transports.BigtableTableAdminRestInterceptor, + "post_test_iam_permissions_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableTableAdminRestInterceptor, "pre_test_iam_permissions" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = iam_policy_pb2.TestIamPermissionsRequest() transcode.return_value = { "method": "post", @@ -23330,6 +23731,7 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson( iam_policy_pb2.TestIamPermissionsResponse() ) @@ -23342,6 +23744,10 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + post_with_metadata.return_value = ( + iam_policy_pb2.TestIamPermissionsResponse(), + metadata, + ) client.test_iam_permissions( request, @@ -23353,6 +23759,7 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_initialize_client_w_rest(): diff --git a/tests/unit/gapic/bigtable_v2/test_bigtable.py b/tests/unit/gapic/bigtable_v2/test_bigtable.py index 10543bd3a..85700b67d 100644 --- a/tests/unit/gapic/bigtable_v2/test_bigtable.py +++ b/tests/unit/gapic/bigtable_v2/test_bigtable.py @@ -67,6 +67,14 @@ import google.auth +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + async def mock_async_gen(data, chunk_size=1): for i in range(0, len(data)): # pragma: NO COVER chunk = data[i : i + chunk_size] @@ -296,6 +304,49 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = BigtableClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = BigtableClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + @pytest.mark.parametrize( "client_class,transport_name", [ @@ -1065,6 +1116,7 @@ def test_read_rows_non_empty_request_with_auto_populated_field(): request = bigtable.ReadRowsRequest( table_name="table_name_value", authorized_view_name="authorized_view_name_value", + materialized_view_name="materialized_view_name_value", app_profile_id="app_profile_id_value", ) @@ -1079,6 +1131,7 @@ def test_read_rows_non_empty_request_with_auto_populated_field(): assert args[0] == bigtable.ReadRowsRequest( table_name="table_name_value", authorized_view_name="authorized_view_name_value", + materialized_view_name="materialized_view_name_value", app_profile_id="app_profile_id_value", ) @@ -1334,6 +1387,7 @@ def test_sample_row_keys_non_empty_request_with_auto_populated_field(): request = bigtable.SampleRowKeysRequest( table_name="table_name_value", authorized_view_name="authorized_view_name_value", + materialized_view_name="materialized_view_name_value", app_profile_id="app_profile_id_value", ) @@ -1348,6 +1402,7 @@ def test_sample_row_keys_non_empty_request_with_auto_populated_field(): assert args[0] == bigtable.SampleRowKeysRequest( table_name="table_name_value", authorized_view_name="authorized_view_name_value", + materialized_view_name="materialized_view_name_value", app_profile_id="app_profile_id_value", ) @@ -3869,6 +3924,292 @@ async def test_read_change_stream_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + bigtable.PrepareQueryRequest, + dict, + ], +) +def test_prepare_query(request_type, transport: str = "grpc"): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable.PrepareQueryResponse( + prepared_query=b"prepared_query_blob", + ) + response = client.prepare_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable.PrepareQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigtable.PrepareQueryResponse) + assert response.prepared_query == b"prepared_query_blob" + + +def test_prepare_query_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable.PrepareQueryRequest( + instance_name="instance_name_value", + app_profile_id="app_profile_id_value", + query="query_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.prepare_query(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == bigtable.PrepareQueryRequest( + instance_name="instance_name_value", + app_profile_id="app_profile_id_value", + query="query_value", + ) + + +def test_prepare_query_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.prepare_query in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.prepare_query] = mock_rpc + request = {} + client.prepare_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.prepare_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_prepare_query_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.prepare_query + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.prepare_query + ] = mock_rpc + + request = {} + await client.prepare_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.prepare_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_prepare_query_async( + transport: str = "grpc_asyncio", request_type=bigtable.PrepareQueryRequest +): + client = BigtableAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable.PrepareQueryResponse( + prepared_query=b"prepared_query_blob", + ) + ) + response = await client.prepare_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable.PrepareQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigtable.PrepareQueryResponse) + assert response.prepared_query == b"prepared_query_blob" + + +@pytest.mark.asyncio +async def test_prepare_query_async_from_dict(): + await test_prepare_query_async(request_type=dict) + + +def test_prepare_query_flattened(): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable.PrepareQueryResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.prepare_query( + instance_name="instance_name_value", + query="query_value", + app_profile_id="app_profile_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].instance_name + mock_val = "instance_name_value" + assert arg == mock_val + arg = args[0].query + mock_val = "query_value" + assert arg == mock_val + arg = args[0].app_profile_id + mock_val = "app_profile_id_value" + assert arg == mock_val + + +def test_prepare_query_flattened_error(): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.prepare_query( + bigtable.PrepareQueryRequest(), + instance_name="instance_name_value", + query="query_value", + app_profile_id="app_profile_id_value", + ) + + +@pytest.mark.asyncio +async def test_prepare_query_flattened_async(): + client = BigtableAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable.PrepareQueryResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable.PrepareQueryResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.prepare_query( + instance_name="instance_name_value", + query="query_value", + app_profile_id="app_profile_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].instance_name + mock_val = "instance_name_value" + assert arg == mock_val + arg = args[0].query + mock_val = "query_value" + assert arg == mock_val + arg = args[0].app_profile_id + mock_val = "app_profile_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_prepare_query_flattened_error_async(): + client = BigtableAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.prepare_query( + bigtable.PrepareQueryRequest(), + instance_name="instance_name_value", + query="query_value", + app_profile_id="app_profile_id_value", + ) + + @pytest.mark.parametrize( "request_type", [ @@ -4218,6 +4559,7 @@ def test_read_rows_rest_flattened(): json_return_value = "[{}]".format(json_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -4318,6 +4660,7 @@ def test_sample_row_keys_rest_flattened(): json_return_value = "[{}]".format(json_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -4451,6 +4794,7 @@ def test_mutate_row_rest_required_fields(request_type=bigtable.MutateRowRequest) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.mutate_row(request) @@ -4513,6 +4857,7 @@ def test_mutate_row_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.mutate_row(**mock_args) @@ -4646,6 +4991,7 @@ def test_mutate_rows_rest_required_fields(request_type=bigtable.MutateRowsReques response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -4698,6 +5044,7 @@ def test_mutate_rows_rest_flattened(): json_return_value = "[{}]".format(json_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -4838,6 +5185,7 @@ def test_check_and_mutate_row_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.check_and_mutate_row(request) @@ -4908,6 +5256,7 @@ def test_check_and_mutate_row_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.check_and_mutate_row(**mock_args) @@ -5061,6 +5410,7 @@ def test_ping_and_warm_rest_required_fields(request_type=bigtable.PingAndWarmReq response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.ping_and_warm(request) @@ -5107,6 +5457,7 @@ def test_ping_and_warm_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.ping_and_warm(**mock_args) @@ -5243,6 +5594,7 @@ def test_read_modify_write_row_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.read_modify_write_row(request) @@ -5301,6 +5653,7 @@ def test_read_modify_write_row_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.read_modify_write_row(**mock_args) @@ -5448,6 +5801,7 @@ def test_generate_initial_change_stream_partitions_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -5505,6 +5859,7 @@ def test_generate_initial_change_stream_partitions_rest_flattened(): json_return_value = "[{}]".format(json_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -5647,6 +6002,7 @@ def test_read_change_stream_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -5698,6 +6054,7 @@ def test_read_change_stream_rest_flattened(): json_return_value = "[{}]".format(json_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -5730,7 +6087,7 @@ def test_read_change_stream_rest_flattened_error(transport: str = "rest"): ) -def test_execute_query_rest_use_cached_wrapped_rpc(): +def test_prepare_query_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5744,29 +6101,29 @@ def test_execute_query_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.execute_query in client._transport._wrapped_methods + assert client._transport.prepare_query in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.execute_query] = mock_rpc + client._transport._wrapped_methods[client._transport.prepare_query] = mock_rpc request = {} - client.execute_query(request) + client.prepare_query(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.execute_query(request) + client.prepare_query(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_execute_query_rest_required_fields(request_type=bigtable.ExecuteQueryRequest): +def test_prepare_query_rest_required_fields(request_type=bigtable.PrepareQueryRequest): transport_class = transports.BigtableRestTransport request_init = {} @@ -5782,7 +6139,201 @@ def test_execute_query_rest_required_fields(request_type=bigtable.ExecuteQueryRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).execute_query._get_unset_required_fields(jsonified_request) + ).prepare_query._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instanceName"] = "instance_name_value" + jsonified_request["query"] = "query_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).prepare_query._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instanceName" in jsonified_request + assert jsonified_request["instanceName"] == "instance_name_value" + assert "query" in jsonified_request + assert jsonified_request["query"] == "query_value" + + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigtable.PrepareQueryResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable.PrepareQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.prepare_query(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_prepare_query_rest_unset_required_fields(): + transport = transports.BigtableRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.prepare_query._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "instanceName", + "query", + "paramTypes", + ) + ) + ) + + +def test_prepare_query_rest_flattened(): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bigtable.PrepareQueryResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"instance_name": "projects/sample1/instances/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + instance_name="instance_name_value", + query="query_value", + app_profile_id="app_profile_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable.PrepareQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.prepare_query(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{instance_name=projects/*/instances/*}:prepareQuery" + % client.transport._host, + args[1], + ) + + +def test_prepare_query_rest_flattened_error(transport: str = "rest"): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.prepare_query( + bigtable.PrepareQueryRequest(), + instance_name="instance_name_value", + query="query_value", + app_profile_id="app_profile_id_value", + ) + + +def test_execute_query_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.execute_query in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.execute_query] = mock_rpc + + request = {} + client.execute_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.execute_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_execute_query_rest_required_fields(request_type=bigtable.ExecuteQueryRequest): + transport_class = transports.BigtableRestTransport + + request_init = {} + request_init["instance_name"] = "" + request_init["query"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).execute_query._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -5836,6 +6387,7 @@ def test_execute_query_rest_required_fields(request_type=bigtable.ExecuteQueryRe response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -5895,6 +6447,7 @@ def test_execute_query_rest_flattened(): json_return_value = "[{}]".format(json_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} with mock.patch.object(response_value, "iter_content") as iter_content: iter_content.return_value = iter(json_return_value) @@ -6233,6 +6786,27 @@ def test_read_change_stream_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_prepare_query_empty_call_grpc(): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + call.return_value = bigtable.PrepareQueryResponse() + client.prepare_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable.PrepareQueryRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_execute_query_empty_call_grpc(): @@ -6846,6 +7420,58 @@ def test_read_modify_write_row_routing_parameters_request_3_grpc(): ) +def test_prepare_query_routing_parameters_request_1_grpc(): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + call.return_value = bigtable.PrepareQueryResponse() + client.prepare_query( + request={"instance_name": "projects/sample1/instances/sample2"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = bigtable.PrepareQueryRequest( + **{"instance_name": "projects/sample1/instances/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"name": "projects/sample1/instances/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_prepare_query_routing_parameters_request_2_grpc(): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + call.return_value = bigtable.PrepareQueryResponse() + client.prepare_query(request={"app_profile_id": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = bigtable.PrepareQueryRequest(**{"app_profile_id": "sample1"}) + + assert args[0] == request_msg + + expected_headers = {"app_profile_id": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + def test_execute_query_routing_parameters_request_1_grpc(): client = BigtableClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6868,11 +7494,7 @@ def test_execute_query_routing_parameters_request_1_grpc(): assert args[0] == request_msg - # expect app_profile_id while temporary patch is in place: https://github.com/googleapis/python-bigtable/pull/1072 - expected_headers = { - "name": "projects/sample1/instances/sample2", - "app_profile_id": "", - } + expected_headers = {"name": "projects/sample1/instances/sample2"} assert ( gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] ) @@ -7156,6 +7778,33 @@ async def test_read_change_stream_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_prepare_query_empty_call_grpc_asyncio(): + client = BigtableAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable.PrepareQueryResponse( + prepared_query=b"prepared_query_blob", + ) + ) + await client.prepare_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable.PrepareQueryRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -7871,6 +8520,70 @@ async def test_read_modify_write_row_routing_parameters_request_3_grpc_asyncio() ) +@pytest.mark.asyncio +async def test_prepare_query_routing_parameters_request_1_grpc_asyncio(): + client = BigtableAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable.PrepareQueryResponse( + prepared_query=b"prepared_query_blob", + ) + ) + await client.prepare_query( + request={"instance_name": "projects/sample1/instances/sample2"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = bigtable.PrepareQueryRequest( + **{"instance_name": "projects/sample1/instances/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"name": "projects/sample1/instances/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_prepare_query_routing_parameters_request_2_grpc_asyncio(): + client = BigtableAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable.PrepareQueryResponse( + prepared_query=b"prepared_query_blob", + ) + ) + await client.prepare_query(request={"app_profile_id": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = bigtable.PrepareQueryRequest(**{"app_profile_id": "sample1"}) + + assert args[0] == request_msg + + expected_headers = {"app_profile_id": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + @pytest.mark.asyncio async def test_execute_query_routing_parameters_request_1_grpc_asyncio(): client = BigtableAsyncClient( @@ -7898,11 +8611,7 @@ async def test_execute_query_routing_parameters_request_1_grpc_asyncio(): assert args[0] == request_msg - # expect app_profile_id while temporary patch is in place: https://github.com/googleapis/python-bigtable/pull/1072 - expected_headers = { - "name": "projects/sample1/instances/sample2", - "app_profile_id": "", - } + expected_headers = {"name": "projects/sample1/instances/sample2"} assert ( gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] ) @@ -7963,6 +8672,7 @@ def test_read_rows_rest_bad_request(request_type=bigtable.ReadRowsRequest): response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.read_rows(request) @@ -7999,6 +8709,7 @@ def test_read_rows_rest_call_success(request_type): json_return_value = "[{}]".format(json_return_value) response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.read_rows(request) assert isinstance(response, Iterable) @@ -8024,10 +8735,13 @@ def test_read_rows_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableRestInterceptor, "post_read_rows" ) as post, mock.patch.object( + transports.BigtableRestInterceptor, "post_read_rows_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableRestInterceptor, "pre_read_rows" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable.ReadRowsRequest.pb(bigtable.ReadRowsRequest()) transcode.return_value = { "method": "post", @@ -8038,6 +8752,7 @@ def test_read_rows_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable.ReadRowsResponse.to_json(bigtable.ReadRowsResponse()) req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) @@ -8048,6 +8763,7 @@ def test_read_rows_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable.ReadRowsResponse() + post_with_metadata.return_value = bigtable.ReadRowsResponse(), metadata client.read_rows( request, @@ -8059,6 +8775,7 @@ def test_read_rows_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_sample_row_keys_rest_bad_request(request_type=bigtable.SampleRowKeysRequest): @@ -8080,6 +8797,7 @@ def test_sample_row_keys_rest_bad_request(request_type=bigtable.SampleRowKeysReq response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.sample_row_keys(request) @@ -8117,6 +8835,7 @@ def test_sample_row_keys_rest_call_success(request_type): json_return_value = "[{}]".format(json_return_value) response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.sample_row_keys(request) assert isinstance(response, Iterable) @@ -8143,10 +8862,13 @@ def test_sample_row_keys_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableRestInterceptor, "post_sample_row_keys" ) as post, mock.patch.object( + transports.BigtableRestInterceptor, "post_sample_row_keys_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableRestInterceptor, "pre_sample_row_keys" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable.SampleRowKeysRequest.pb(bigtable.SampleRowKeysRequest()) transcode.return_value = { "method": "post", @@ -8157,6 +8879,7 @@ def test_sample_row_keys_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable.SampleRowKeysResponse.to_json( bigtable.SampleRowKeysResponse() ) @@ -8169,6 +8892,7 @@ def test_sample_row_keys_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable.SampleRowKeysResponse() + post_with_metadata.return_value = bigtable.SampleRowKeysResponse(), metadata client.sample_row_keys( request, @@ -8180,6 +8904,7 @@ def test_sample_row_keys_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_mutate_row_rest_bad_request(request_type=bigtable.MutateRowRequest): @@ -8201,6 +8926,7 @@ def test_mutate_row_rest_bad_request(request_type=bigtable.MutateRowRequest): response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.mutate_row(request) @@ -8234,6 +8960,7 @@ def test_mutate_row_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.mutate_row(request) # Establish that the response is the type that we expect. @@ -8255,10 +8982,13 @@ def test_mutate_row_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableRestInterceptor, "post_mutate_row" ) as post, mock.patch.object( + transports.BigtableRestInterceptor, "post_mutate_row_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableRestInterceptor, "pre_mutate_row" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable.MutateRowRequest.pb(bigtable.MutateRowRequest()) transcode.return_value = { "method": "post", @@ -8269,6 +8999,7 @@ def test_mutate_row_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable.MutateRowResponse.to_json(bigtable.MutateRowResponse()) req.return_value.content = return_value @@ -8279,6 +9010,7 @@ def test_mutate_row_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable.MutateRowResponse() + post_with_metadata.return_value = bigtable.MutateRowResponse(), metadata client.mutate_row( request, @@ -8290,6 +9022,7 @@ def test_mutate_row_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_mutate_rows_rest_bad_request(request_type=bigtable.MutateRowsRequest): @@ -8311,6 +9044,7 @@ def test_mutate_rows_rest_bad_request(request_type=bigtable.MutateRowsRequest): response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.mutate_rows(request) @@ -8345,6 +9079,7 @@ def test_mutate_rows_rest_call_success(request_type): json_return_value = "[{}]".format(json_return_value) response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.mutate_rows(request) assert isinstance(response, Iterable) @@ -8369,10 +9104,13 @@ def test_mutate_rows_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableRestInterceptor, "post_mutate_rows" ) as post, mock.patch.object( + transports.BigtableRestInterceptor, "post_mutate_rows_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableRestInterceptor, "pre_mutate_rows" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable.MutateRowsRequest.pb(bigtable.MutateRowsRequest()) transcode.return_value = { "method": "post", @@ -8383,6 +9121,7 @@ def test_mutate_rows_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable.MutateRowsResponse.to_json( bigtable.MutateRowsResponse() ) @@ -8395,6 +9134,7 @@ def test_mutate_rows_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable.MutateRowsResponse() + post_with_metadata.return_value = bigtable.MutateRowsResponse(), metadata client.mutate_rows( request, @@ -8406,6 +9146,7 @@ def test_mutate_rows_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_check_and_mutate_row_rest_bad_request( @@ -8429,6 +9170,7 @@ def test_check_and_mutate_row_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.check_and_mutate_row(request) @@ -8464,6 +9206,7 @@ def test_check_and_mutate_row_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.check_and_mutate_row(request) # Establish that the response is the type that we expect. @@ -8486,10 +9229,13 @@ def test_check_and_mutate_row_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableRestInterceptor, "post_check_and_mutate_row" ) as post, mock.patch.object( + transports.BigtableRestInterceptor, "post_check_and_mutate_row_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableRestInterceptor, "pre_check_and_mutate_row" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable.CheckAndMutateRowRequest.pb( bigtable.CheckAndMutateRowRequest() ) @@ -8502,6 +9248,7 @@ def test_check_and_mutate_row_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable.CheckAndMutateRowResponse.to_json( bigtable.CheckAndMutateRowResponse() ) @@ -8514,6 +9261,7 @@ def test_check_and_mutate_row_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable.CheckAndMutateRowResponse() + post_with_metadata.return_value = bigtable.CheckAndMutateRowResponse(), metadata client.check_and_mutate_row( request, @@ -8525,6 +9273,7 @@ def test_check_and_mutate_row_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_ping_and_warm_rest_bad_request(request_type=bigtable.PingAndWarmRequest): @@ -8546,6 +9295,7 @@ def test_ping_and_warm_rest_bad_request(request_type=bigtable.PingAndWarmRequest response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.ping_and_warm(request) @@ -8579,6 +9329,7 @@ def test_ping_and_warm_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.ping_and_warm(request) # Establish that the response is the type that we expect. @@ -8600,10 +9351,13 @@ def test_ping_and_warm_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableRestInterceptor, "post_ping_and_warm" ) as post, mock.patch.object( + transports.BigtableRestInterceptor, "post_ping_and_warm_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableRestInterceptor, "pre_ping_and_warm" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable.PingAndWarmRequest.pb(bigtable.PingAndWarmRequest()) transcode.return_value = { "method": "post", @@ -8614,6 +9368,7 @@ def test_ping_and_warm_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable.PingAndWarmResponse.to_json( bigtable.PingAndWarmResponse() ) @@ -8626,6 +9381,7 @@ def test_ping_and_warm_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable.PingAndWarmResponse() + post_with_metadata.return_value = bigtable.PingAndWarmResponse(), metadata client.ping_and_warm( request, @@ -8637,6 +9393,7 @@ def test_ping_and_warm_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_read_modify_write_row_rest_bad_request( @@ -8660,6 +9417,7 @@ def test_read_modify_write_row_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.read_modify_write_row(request) @@ -8693,6 +9451,7 @@ def test_read_modify_write_row_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.read_modify_write_row(request) # Establish that the response is the type that we expect. @@ -8714,10 +9473,13 @@ def test_read_modify_write_row_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableRestInterceptor, "post_read_modify_write_row" ) as post, mock.patch.object( + transports.BigtableRestInterceptor, "post_read_modify_write_row_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableRestInterceptor, "pre_read_modify_write_row" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable.ReadModifyWriteRowRequest.pb( bigtable.ReadModifyWriteRowRequest() ) @@ -8730,6 +9492,7 @@ def test_read_modify_write_row_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable.ReadModifyWriteRowResponse.to_json( bigtable.ReadModifyWriteRowResponse() ) @@ -8742,6 +9505,10 @@ def test_read_modify_write_row_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable.ReadModifyWriteRowResponse() + post_with_metadata.return_value = ( + bigtable.ReadModifyWriteRowResponse(), + metadata, + ) client.read_modify_write_row( request, @@ -8753,6 +9520,7 @@ def test_read_modify_write_row_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_generate_initial_change_stream_partitions_rest_bad_request( @@ -8776,6 +9544,7 @@ def test_generate_initial_change_stream_partitions_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.generate_initial_change_stream_partitions(request) @@ -8812,6 +9581,7 @@ def test_generate_initial_change_stream_partitions_rest_call_success(request_typ json_return_value = "[{}]".format(json_return_value) response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_initial_change_stream_partitions(request) assert isinstance(response, Iterable) @@ -8837,11 +9607,15 @@ def test_generate_initial_change_stream_partitions_rest_interceptors(null_interc transports.BigtableRestInterceptor, "post_generate_initial_change_stream_partitions", ) as post, mock.patch.object( + transports.BigtableRestInterceptor, + "post_generate_initial_change_stream_partitions_with_metadata", + ) as post_with_metadata, mock.patch.object( transports.BigtableRestInterceptor, "pre_generate_initial_change_stream_partitions", ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable.GenerateInitialChangeStreamPartitionsRequest.pb( bigtable.GenerateInitialChangeStreamPartitionsRequest() ) @@ -8854,6 +9628,7 @@ def test_generate_initial_change_stream_partitions_rest_interceptors(null_interc req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable.GenerateInitialChangeStreamPartitionsResponse.to_json( bigtable.GenerateInitialChangeStreamPartitionsResponse() ) @@ -8866,6 +9641,10 @@ def test_generate_initial_change_stream_partitions_rest_interceptors(null_interc ] pre.return_value = request, metadata post.return_value = bigtable.GenerateInitialChangeStreamPartitionsResponse() + post_with_metadata.return_value = ( + bigtable.GenerateInitialChangeStreamPartitionsResponse(), + metadata, + ) client.generate_initial_change_stream_partitions( request, @@ -8877,6 +9656,7 @@ def test_generate_initial_change_stream_partitions_rest_interceptors(null_interc pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_read_change_stream_rest_bad_request( @@ -8900,6 +9680,7 @@ def test_read_change_stream_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.read_change_stream(request) @@ -8934,6 +9715,7 @@ def test_read_change_stream_rest_call_success(request_type): json_return_value = "[{}]".format(json_return_value) response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.read_change_stream(request) assert isinstance(response, Iterable) @@ -8958,10 +9740,13 @@ def test_read_change_stream_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableRestInterceptor, "post_read_change_stream" ) as post, mock.patch.object( + transports.BigtableRestInterceptor, "post_read_change_stream_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableRestInterceptor, "pre_read_change_stream" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable.ReadChangeStreamRequest.pb( bigtable.ReadChangeStreamRequest() ) @@ -8974,6 +9759,7 @@ def test_read_change_stream_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable.ReadChangeStreamResponse.to_json( bigtable.ReadChangeStreamResponse() ) @@ -8986,6 +9772,7 @@ def test_read_change_stream_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable.ReadChangeStreamResponse() + post_with_metadata.return_value = bigtable.ReadChangeStreamResponse(), metadata client.read_change_stream( request, @@ -8997,6 +9784,130 @@ def test_read_change_stream_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_prepare_query_rest_bad_request(request_type=bigtable.PrepareQueryRequest): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"instance_name": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.prepare_query(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable.PrepareQueryRequest, + dict, + ], +) +def test_prepare_query_rest_call_success(request_type): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"instance_name": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bigtable.PrepareQueryResponse( + prepared_query=b"prepared_query_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable.PrepareQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.prepare_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigtable.PrepareQueryResponse) + assert response.prepared_query == b"prepared_query_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_prepare_query_rest_interceptors(null_interceptor): + transport = transports.BigtableRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BigtableRestInterceptor(), + ) + client = BigtableClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BigtableRestInterceptor, "post_prepare_query" + ) as post, mock.patch.object( + transports.BigtableRestInterceptor, "post_prepare_query_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.BigtableRestInterceptor, "pre_prepare_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable.PrepareQueryRequest.pb(bigtable.PrepareQueryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = bigtable.PrepareQueryResponse.to_json( + bigtable.PrepareQueryResponse() + ) + req.return_value.content = return_value + + request = bigtable.PrepareQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigtable.PrepareQueryResponse() + post_with_metadata.return_value = bigtable.PrepareQueryResponse(), metadata + + client.prepare_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() def test_execute_query_rest_bad_request(request_type=bigtable.ExecuteQueryRequest): @@ -9018,6 +9929,7 @@ def test_execute_query_rest_bad_request(request_type=bigtable.ExecuteQueryReques response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.execute_query(request) @@ -9052,6 +9964,7 @@ def test_execute_query_rest_call_success(request_type): json_return_value = "[{}]".format(json_return_value) response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.execute_query(request) assert isinstance(response, Iterable) @@ -9076,10 +9989,13 @@ def test_execute_query_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( transports.BigtableRestInterceptor, "post_execute_query" ) as post, mock.patch.object( + transports.BigtableRestInterceptor, "post_execute_query_with_metadata" + ) as post_with_metadata, mock.patch.object( transports.BigtableRestInterceptor, "pre_execute_query" ) as pre: pre.assert_not_called() post.assert_not_called() + post_with_metadata.assert_not_called() pb_message = bigtable.ExecuteQueryRequest.pb(bigtable.ExecuteQueryRequest()) transcode.return_value = { "method": "post", @@ -9090,6 +10006,7 @@ def test_execute_query_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = bigtable.ExecuteQueryResponse.to_json( bigtable.ExecuteQueryResponse() ) @@ -9102,6 +10019,7 @@ def test_execute_query_rest_interceptors(null_interceptor): ] pre.return_value = request, metadata post.return_value = bigtable.ExecuteQueryResponse() + post_with_metadata.return_value = bigtable.ExecuteQueryResponse(), metadata client.execute_query( request, @@ -9113,6 +10031,7 @@ def test_execute_query_rest_interceptors(null_interceptor): pre.assert_called_once() post.assert_called_once() + post_with_metadata.assert_called_once() def test_initialize_client_w_rest(): @@ -9310,6 +10229,26 @@ def test_read_change_stream_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_prepare_query_empty_call_rest(): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + client.prepare_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable.PrepareQueryRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_execute_query_empty_call_rest(): @@ -9902,6 +10841,56 @@ def test_read_modify_write_row_routing_parameters_request_3_rest(): ) +def test_prepare_query_routing_parameters_request_1_rest(): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + client.prepare_query( + request={"instance_name": "projects/sample1/instances/sample2"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = bigtable.PrepareQueryRequest( + **{"instance_name": "projects/sample1/instances/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"name": "projects/sample1/instances/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_prepare_query_routing_parameters_request_2_rest(): + client = BigtableClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.prepare_query), "__call__") as call: + client.prepare_query(request={"app_profile_id": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = bigtable.PrepareQueryRequest(**{"app_profile_id": "sample1"}) + + assert args[0] == request_msg + + expected_headers = {"app_profile_id": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + def test_execute_query_routing_parameters_request_1_rest(): client = BigtableClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9923,11 +10912,7 @@ def test_execute_query_routing_parameters_request_1_rest(): assert args[0] == request_msg - # expect app_profile_id while temporary patch is in place: https://github.com/googleapis/python-bigtable/pull/1072 - expected_headers = { - "name": "projects/sample1/instances/sample2", - "app_profile_id": "", - } + expected_headers = {"name": "projects/sample1/instances/sample2"} assert ( gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] ) @@ -9998,6 +10983,7 @@ def test_bigtable_base_transport(): "read_modify_write_row", "generate_initial_change_stream_partitions", "read_change_stream", + "prepare_query", "execute_query", ) for method in methods: @@ -10309,6 +11295,9 @@ def test_bigtable_client_transport_session_collision(transport_name): session1 = client1.transport.read_change_stream._session session2 = client2.transport.read_change_stream._session assert session1 != session2 + session1 = client1.transport.prepare_query._session + session2 = client2.transport.prepare_query._session + assert session1 != session2 session1 = client1.transport.execute_query._session session2 = client2.transport.execute_query._session assert session1 != session2 @@ -10486,10 +11475,36 @@ def test_parse_instance_path(): assert expected == actual -def test_table_path(): +def test_materialized_view_path(): project = "squid" instance = "clam" - table = "whelk" + materialized_view = "whelk" + expected = "projects/{project}/instances/{instance}/materializedViews/{materialized_view}".format( + project=project, + instance=instance, + materialized_view=materialized_view, + ) + actual = BigtableClient.materialized_view_path(project, instance, materialized_view) + assert expected == actual + + +def test_parse_materialized_view_path(): + expected = { + "project": "octopus", + "instance": "oyster", + "materialized_view": "nudibranch", + } + path = BigtableClient.materialized_view_path(**expected) + + # Check that the path construction is reversible. + actual = BigtableClient.parse_materialized_view_path(path) + assert expected == actual + + +def test_table_path(): + project = "cuttlefish" + instance = "mussel" + table = "winkle" expected = "projects/{project}/instances/{instance}/tables/{table}".format( project=project, instance=instance, @@ -10501,9 +11516,9 @@ def test_table_path(): def test_parse_table_path(): expected = { - "project": "octopus", - "instance": "oyster", - "table": "nudibranch", + "project": "nautilus", + "instance": "scallop", + "table": "abalone", } path = BigtableClient.table_path(**expected) @@ -10513,7 +11528,7 @@ def test_parse_table_path(): def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -10523,7 +11538,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "clam", } path = BigtableClient.common_billing_account_path(**expected) @@ -10533,7 +11548,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -10543,7 +11558,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "octopus", } path = BigtableClient.common_folder_path(**expected) @@ -10553,7 +11568,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -10563,7 +11578,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "nudibranch", } path = BigtableClient.common_organization_path(**expected) @@ -10573,7 +11588,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -10583,7 +11598,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "mussel", } path = BigtableClient.common_project_path(**expected) @@ -10593,8 +11608,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -10605,8 +11620,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "scallop", + "location": "abalone", } path = BigtableClient.common_location_path(**expected)