diff --git a/gapic/schema/api.py b/gapic/schema/api.py index 21b87542df..c48bf4db68 100644 --- a/gapic/schema/api.py +++ b/gapic/schema/api.py @@ -24,7 +24,7 @@ import os import sys from types import MappingProxyType -from typing import Callable, Container, Dict, FrozenSet, Mapping, Optional, Sequence, Set, Tuple +from typing import Callable, Container, Dict, FrozenSet, Iterable, Mapping, Optional, Sequence, Set, Tuple import yaml from google.api_core import exceptions diff --git a/tests/integration/goldens/redis/google/cloud/redis/__init__.py b/tests/integration/goldens/redis/google/cloud/redis/__init__.py index ededc2d374..527bad46ac 100755 --- a/tests/integration/goldens/redis/google/cloud/redis/__init__.py +++ b/tests/integration/goldens/redis/google/cloud/redis/__init__.py @@ -23,59 +23,33 @@ from google.cloud.redis_v1.types.cloud_redis import CreateInstanceRequest from google.cloud.redis_v1.types.cloud_redis import DeleteInstanceRequest -from google.cloud.redis_v1.types.cloud_redis import ExportInstanceRequest -from google.cloud.redis_v1.types.cloud_redis import FailoverInstanceRequest -from google.cloud.redis_v1.types.cloud_redis import GcsDestination -from google.cloud.redis_v1.types.cloud_redis import GcsSource -from google.cloud.redis_v1.types.cloud_redis import GetInstanceAuthStringRequest from google.cloud.redis_v1.types.cloud_redis import GetInstanceRequest -from google.cloud.redis_v1.types.cloud_redis import ImportInstanceRequest -from google.cloud.redis_v1.types.cloud_redis import InputConfig from google.cloud.redis_v1.types.cloud_redis import Instance -from google.cloud.redis_v1.types.cloud_redis import InstanceAuthString from google.cloud.redis_v1.types.cloud_redis import ListInstancesRequest from google.cloud.redis_v1.types.cloud_redis import ListInstancesResponse -from google.cloud.redis_v1.types.cloud_redis import LocationMetadata from google.cloud.redis_v1.types.cloud_redis import MaintenancePolicy from google.cloud.redis_v1.types.cloud_redis import MaintenanceSchedule from google.cloud.redis_v1.types.cloud_redis import NodeInfo from google.cloud.redis_v1.types.cloud_redis import OperationMetadata -from google.cloud.redis_v1.types.cloud_redis import OutputConfig from google.cloud.redis_v1.types.cloud_redis import PersistenceConfig -from google.cloud.redis_v1.types.cloud_redis import RescheduleMaintenanceRequest from google.cloud.redis_v1.types.cloud_redis import TlsCertificate from google.cloud.redis_v1.types.cloud_redis import UpdateInstanceRequest -from google.cloud.redis_v1.types.cloud_redis import UpgradeInstanceRequest from google.cloud.redis_v1.types.cloud_redis import WeeklyMaintenanceWindow -from google.cloud.redis_v1.types.cloud_redis import ZoneMetadata __all__ = ('CloudRedisClient', 'CloudRedisAsyncClient', 'CreateInstanceRequest', 'DeleteInstanceRequest', - 'ExportInstanceRequest', - 'FailoverInstanceRequest', - 'GcsDestination', - 'GcsSource', - 'GetInstanceAuthStringRequest', 'GetInstanceRequest', - 'ImportInstanceRequest', - 'InputConfig', 'Instance', - 'InstanceAuthString', 'ListInstancesRequest', 'ListInstancesResponse', - 'LocationMetadata', 'MaintenancePolicy', 'MaintenanceSchedule', 'NodeInfo', 'OperationMetadata', - 'OutputConfig', 'PersistenceConfig', - 'RescheduleMaintenanceRequest', 'TlsCertificate', 'UpdateInstanceRequest', - 'UpgradeInstanceRequest', 'WeeklyMaintenanceWindow', - 'ZoneMetadata', ) diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py b/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py index e89fe0cc8a..797596a679 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py @@ -23,60 +23,34 @@ from .types.cloud_redis import CreateInstanceRequest from .types.cloud_redis import DeleteInstanceRequest -from .types.cloud_redis import ExportInstanceRequest -from .types.cloud_redis import FailoverInstanceRequest -from .types.cloud_redis import GcsDestination -from .types.cloud_redis import GcsSource -from .types.cloud_redis import GetInstanceAuthStringRequest from .types.cloud_redis import GetInstanceRequest -from .types.cloud_redis import ImportInstanceRequest -from .types.cloud_redis import InputConfig from .types.cloud_redis import Instance -from .types.cloud_redis import InstanceAuthString from .types.cloud_redis import ListInstancesRequest from .types.cloud_redis import ListInstancesResponse -from .types.cloud_redis import LocationMetadata from .types.cloud_redis import MaintenancePolicy from .types.cloud_redis import MaintenanceSchedule from .types.cloud_redis import NodeInfo from .types.cloud_redis import OperationMetadata -from .types.cloud_redis import OutputConfig from .types.cloud_redis import PersistenceConfig -from .types.cloud_redis import RescheduleMaintenanceRequest from .types.cloud_redis import TlsCertificate from .types.cloud_redis import UpdateInstanceRequest -from .types.cloud_redis import UpgradeInstanceRequest from .types.cloud_redis import WeeklyMaintenanceWindow -from .types.cloud_redis import ZoneMetadata __all__ = ( 'CloudRedisAsyncClient', 'CloudRedisClient', 'CreateInstanceRequest', 'DeleteInstanceRequest', -'ExportInstanceRequest', -'FailoverInstanceRequest', -'GcsDestination', -'GcsSource', -'GetInstanceAuthStringRequest', 'GetInstanceRequest', -'ImportInstanceRequest', -'InputConfig', 'Instance', -'InstanceAuthString', 'ListInstancesRequest', 'ListInstancesResponse', -'LocationMetadata', 'MaintenancePolicy', 'MaintenanceSchedule', 'NodeInfo', 'OperationMetadata', -'OutputConfig', 'PersistenceConfig', -'RescheduleMaintenanceRequest', 'TlsCertificate', 'UpdateInstanceRequest', -'UpgradeInstanceRequest', 'WeeklyMaintenanceWindow', -'ZoneMetadata', ) diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/gapic_metadata.json b/tests/integration/goldens/redis/google/cloud/redis_v1/gapic_metadata.json index 202306de2c..4f1451dba1 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/gapic_metadata.json +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/gapic_metadata.json @@ -20,50 +20,20 @@ "delete_instance" ] }, - "ExportInstance": { - "methods": [ - "export_instance" - ] - }, - "FailoverInstance": { - "methods": [ - "failover_instance" - ] - }, "GetInstance": { "methods": [ "get_instance" ] }, - "GetInstanceAuthString": { - "methods": [ - "get_instance_auth_string" - ] - }, - "ImportInstance": { - "methods": [ - "import_instance" - ] - }, "ListInstances": { "methods": [ "list_instances" ] }, - "RescheduleMaintenance": { - "methods": [ - "reschedule_maintenance" - ] - }, "UpdateInstance": { "methods": [ "update_instance" ] - }, - "UpgradeInstance": { - "methods": [ - "upgrade_instance" - ] } } }, @@ -80,50 +50,20 @@ "delete_instance" ] }, - "ExportInstance": { - "methods": [ - "export_instance" - ] - }, - "FailoverInstance": { - "methods": [ - "failover_instance" - ] - }, "GetInstance": { "methods": [ "get_instance" ] }, - "GetInstanceAuthString": { - "methods": [ - "get_instance_auth_string" - ] - }, - "ImportInstance": { - "methods": [ - "import_instance" - ] - }, "ListInstances": { "methods": [ "list_instances" ] }, - "RescheduleMaintenance": { - "methods": [ - "reschedule_maintenance" - ] - }, "UpdateInstance": { "methods": [ "update_instance" ] - }, - "UpgradeInstance": { - "methods": [ - "upgrade_instance" - ] } } }, @@ -140,50 +80,20 @@ "delete_instance" ] }, - "ExportInstance": { - "methods": [ - "export_instance" - ] - }, - "FailoverInstance": { - "methods": [ - "failover_instance" - ] - }, "GetInstance": { "methods": [ "get_instance" ] }, - "GetInstanceAuthString": { - "methods": [ - "get_instance_auth_string" - ] - }, - "ImportInstance": { - "methods": [ - "import_instance" - ] - }, "ListInstances": { "methods": [ "list_instances" ] }, - "RescheduleMaintenance": { - "methods": [ - "reschedule_maintenance" - ] - }, "UpdateInstance": { "methods": [ "update_instance" ] - }, - "UpgradeInstance": { - "methods": [ - "upgrade_instance" - ] } } } diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py index 2ba2cb14de..233a17a6ed 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py @@ -512,113 +512,6 @@ async def sample_get_instance(): # Done; return the response. return response - async def get_instance_auth_string(self, - request: Optional[Union[cloud_redis.GetInstanceAuthStringRequest, 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]]] = (), - ) -> cloud_redis.InstanceAuthString: - r"""Gets the AUTH string for a Redis instance. If AUTH is - not enabled for the instance the response will be empty. - This information is not included in the details returned - to GetInstance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - async def sample_get_instance_auth_string(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - request = redis_v1.GetInstanceAuthStringRequest( - name="name_value", - ) - - # Make the request - response = await client.get_instance_auth_string(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.redis_v1.types.GetInstanceAuthStringRequest, dict]]): - The request object. Request for - [GetInstanceAuthString][google.cloud.redis.v1.CloudRedis.GetInstanceAuthString]. - name (:class:`str`): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - 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.redis_v1.types.InstanceAuthString: - Instance AUTH string details. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, cloud_redis.GetInstanceAuthStringRequest): - request = cloud_redis.GetInstanceAuthStringRequest(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_instance_auth_string] - - # 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 create_instance(self, request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, *, @@ -934,17 +827,16 @@ async def sample_update_instance(): # Done; return the response. return response - async def upgrade_instance(self, - request: Optional[Union[cloud_redis.UpgradeInstanceRequest, dict]] = None, + async def delete_instance(self, + request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, *, name: Optional[str] = None, - redis_version: 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"""Upgrades Redis instance to the newer Redis version - specified in the request. + r"""Deletes a specific Redis instance. Instance stops + serving and data is deleted. .. code-block:: python @@ -957,18 +849,17 @@ async def upgrade_instance(self, # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import redis_v1 - async def sample_upgrade_instance(): + async def sample_delete_instance(): # Create a client client = redis_v1.CloudRedisAsyncClient() # Initialize request argument(s) - request = redis_v1.UpgradeInstanceRequest( + request = redis_v1.DeleteInstanceRequest( name="name_value", - redis_version="redis_version_value", ) # Make the request - operation = client.upgrade_instance(request=request) + operation = client.delete_instance(request=request) print("Waiting for operation to complete...") @@ -978,9 +869,9 @@ async def sample_upgrade_instance(): print(response) Args: - request (Optional[Union[google.cloud.redis_v1.types.UpgradeInstanceRequest, dict]]): + request (Optional[Union[google.cloud.redis_v1.types.DeleteInstanceRequest, dict]]): The request object. Request for - [UpgradeInstance][google.cloud.redis.v1.CloudRedis.UpgradeInstance]. + [DeleteInstance][google.cloud.redis.v1.CloudRedis.DeleteInstance]. name (:class:`str`): Required. Redis instance resource name using the form: ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` @@ -989,13 +880,6 @@ async def sample_upgrade_instance(): This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - redis_version (:class:`str`): - Required. Specifies the target - version of Redis software to upgrade to. - - This corresponds to the ``redis_version`` 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. @@ -1008,580 +892,39 @@ async def sample_upgrade_instance(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be - :class:`google.cloud.redis_v1.types.Instance` A - Memorystore for Redis 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, redis_version]) - if request is 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, cloud_redis.UpgradeInstanceRequest): - request = cloud_redis.UpgradeInstanceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if redis_version is not None: - request.redis_version = redis_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.upgrade_instance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - cloud_redis.Instance, - metadata_type=cloud_redis.OperationMetadata, - ) - - # Done; return the response. - return response - - async def import_instance(self, - request: Optional[Union[cloud_redis.ImportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - input_config: Optional[cloud_redis.InputConfig] = 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"""Import a Redis RDB snapshot file from Cloud Storage - into a Redis instance. - Redis may stop serving during this operation. Instance - state will be IMPORTING for entire operation. When - complete, the instance will contain only data from the - imported file. - - The returned operation is automatically deleted after a - few hours, so there is no need to call DeleteOperation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - async def sample_import_instance(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - input_config = redis_v1.InputConfig() - input_config.gcs_source.uri = "uri_value" - - request = redis_v1.ImportInstanceRequest( - name="name_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.redis_v1.types.ImportInstanceRequest, dict]]): - The request object. Request for - [Import][google.cloud.redis.v1.CloudRedis.ImportInstance]. - name (:class:`str`): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - input_config (:class:`google.cloud.redis_v1.types.InputConfig`): - Required. Specify data to be - imported. - - This corresponds to the ``input_config`` 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`. + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); - The result type for the operation will be - :class:`google.cloud.redis_v1.types.Instance` A - Memorystore for Redis 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, input_config]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError("If the `request` argument is set, then none of " "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, cloud_redis.ImportInstanceRequest): - request = cloud_redis.ImportInstanceRequest(request) + if not isinstance(request, cloud_redis.DeleteInstanceRequest): + request = cloud_redis.DeleteInstanceRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name - if input_config is not None: - request.input_config = input_config # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.import_instance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - cloud_redis.Instance, - metadata_type=cloud_redis.OperationMetadata, - ) - - # Done; return the response. - return response - - async def export_instance(self, - request: Optional[Union[cloud_redis.ExportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - output_config: Optional[cloud_redis.OutputConfig] = 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"""Export Redis instance data into a Redis RDB format - file in Cloud Storage. - Redis will continue serving during this operation. - - The returned operation is automatically deleted after a - few hours, so there is no need to call DeleteOperation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - async def sample_export_instance(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - output_config = redis_v1.OutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = redis_v1.ExportInstanceRequest( - name="name_value", - output_config=output_config, - ) - - # Make the request - operation = client.export_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.redis_v1.types.ExportInstanceRequest, dict]]): - The request object. Request for - [Export][google.cloud.redis.v1.CloudRedis.ExportInstance]. - name (:class:`str`): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - output_config (:class:`google.cloud.redis_v1.types.OutputConfig`): - Required. Specify data to be - exported. - - This corresponds to the ``output_config`` 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.redis_v1.types.Instance` A - Memorystore for Redis 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, output_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, cloud_redis.ExportInstanceRequest): - request = cloud_redis.ExportInstanceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if output_config is not None: - request.output_config = output_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.export_instance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - cloud_redis.Instance, - metadata_type=cloud_redis.OperationMetadata, - ) - - # Done; return the response. - return response - - async def failover_instance(self, - request: Optional[Union[cloud_redis.FailoverInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - data_protection_mode: Optional[cloud_redis.FailoverInstanceRequest.DataProtectionMode] = 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"""Initiates a failover of the primary node to current - replica node for a specific STANDARD tier Cloud - Memorystore for Redis instance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - async def sample_failover_instance(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - request = redis_v1.FailoverInstanceRequest( - name="name_value", - ) - - # Make the request - operation = client.failover_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.redis_v1.types.FailoverInstanceRequest, dict]]): - The request object. Request for - [Failover][google.cloud.redis.v1.CloudRedis.FailoverInstance]. - name (:class:`str`): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data_protection_mode (:class:`google.cloud.redis_v1.types.FailoverInstanceRequest.DataProtectionMode`): - Optional. Available data protection modes that the user - can choose. If it's unspecified, data protection mode - will be LIMITED_DATA_LOSS by default. - - This corresponds to the ``data_protection_mode`` 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.redis_v1.types.Instance` A - Memorystore for Redis 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, data_protection_mode]) - if request is 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, cloud_redis.FailoverInstanceRequest): - request = cloud_redis.FailoverInstanceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data_protection_mode is not None: - request.data_protection_mode = data_protection_mode - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.failover_instance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - cloud_redis.Instance, - metadata_type=cloud_redis.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_instance(self, - request: Optional[Union[cloud_redis.DeleteInstanceRequest, 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]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a specific Redis instance. Instance stops - serving and data is deleted. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - async def sample_delete_instance(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - request = redis_v1.DeleteInstanceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.redis_v1.types.DeleteInstanceRequest, dict]]): - The request object. Request for - [DeleteInstance][google.cloud.redis.v1.CloudRedis.DeleteInstance]. - name (:class:`str`): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, cloud_redis.DeleteInstanceRequest): - request = cloud_redis.DeleteInstanceRequest(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_instance] + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_instance] # Certain fields should be provided within the metadata header; # add these here. @@ -1613,150 +956,6 @@ async def sample_delete_instance(): # Done; return the response. return response - async def reschedule_maintenance(self, - request: Optional[Union[cloud_redis.RescheduleMaintenanceRequest, dict]] = None, - *, - name: Optional[str] = None, - reschedule_type: Optional[cloud_redis.RescheduleMaintenanceRequest.RescheduleType] = None, - schedule_time: Optional[timestamp_pb2.Timestamp] = 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"""Reschedule maintenance for a given instance in a - given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - async def sample_reschedule_maintenance(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - request = redis_v1.RescheduleMaintenanceRequest( - name="name_value", - reschedule_type="SPECIFIC_TIME", - ) - - # Make the request - operation = client.reschedule_maintenance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.redis_v1.types.RescheduleMaintenanceRequest, dict]]): - The request object. Request for - [RescheduleMaintenance][google.cloud.redis.v1.CloudRedis.RescheduleMaintenance]. - name (:class:`str`): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - reschedule_type (:class:`google.cloud.redis_v1.types.RescheduleMaintenanceRequest.RescheduleType`): - Required. If reschedule type is SPECIFIC_TIME, must set - up schedule_time as well. - - This corresponds to the ``reschedule_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schedule_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Optional. Timestamp when the maintenance shall be - rescheduled to if reschedule_type=SPECIFIC_TIME, in RFC - 3339 format, for example ``2012-11-15T16:19:00.094Z``. - - This corresponds to the ``schedule_time`` 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.redis_v1.types.Instance` A - Memorystore for Redis 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, reschedule_type, schedule_time]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, cloud_redis.RescheduleMaintenanceRequest): - request = cloud_redis.RescheduleMaintenanceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if reschedule_type is not None: - request.reschedule_type = reschedule_type - if schedule_time is not None: - request.schedule_time = schedule_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.reschedule_maintenance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - cloud_redis.Instance, - metadata_type=cloud_redis.OperationMetadata, - ) - - # Done; return the response. - return response - async def list_operations( self, request: Optional[operations_pb2.ListOperationsRequest] = None, diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index efdfcd898c..848541a836 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -865,112 +865,6 @@ def sample_get_instance(): # Done; return the response. return response - def get_instance_auth_string(self, - request: Optional[Union[cloud_redis.GetInstanceAuthStringRequest, 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]]] = (), - ) -> cloud_redis.InstanceAuthString: - r"""Gets the AUTH string for a Redis instance. If AUTH is - not enabled for the instance the response will be empty. - This information is not included in the details returned - to GetInstance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - def sample_get_instance_auth_string(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - request = redis_v1.GetInstanceAuthStringRequest( - name="name_value", - ) - - # Make the request - response = client.get_instance_auth_string(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.redis_v1.types.GetInstanceAuthStringRequest, dict]): - The request object. Request for - [GetInstanceAuthString][google.cloud.redis.v1.CloudRedis.GetInstanceAuthString]. - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - 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.redis_v1.types.InstanceAuthString: - Instance AUTH string details. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, cloud_redis.GetInstanceAuthStringRequest): - request = cloud_redis.GetInstanceAuthStringRequest(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_instance_auth_string] - - # 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 create_instance(self, request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, *, @@ -1284,17 +1178,16 @@ def sample_update_instance(): # Done; return the response. return response - def upgrade_instance(self, - request: Optional[Union[cloud_redis.UpgradeInstanceRequest, dict]] = None, + def delete_instance(self, + request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, *, name: Optional[str] = None, - redis_version: 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"""Upgrades Redis instance to the newer Redis version - specified in the request. + r"""Deletes a specific Redis instance. Instance stops + serving and data is deleted. .. code-block:: python @@ -1307,18 +1200,17 @@ def upgrade_instance(self, # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import redis_v1 - def sample_upgrade_instance(): + def sample_delete_instance(): # Create a client client = redis_v1.CloudRedisClient() # Initialize request argument(s) - request = redis_v1.UpgradeInstanceRequest( + request = redis_v1.DeleteInstanceRequest( name="name_value", - redis_version="redis_version_value", ) # Make the request - operation = client.upgrade_instance(request=request) + operation = client.delete_instance(request=request) print("Waiting for operation to complete...") @@ -1328,9 +1220,9 @@ def sample_upgrade_instance(): print(response) Args: - request (Union[google.cloud.redis_v1.types.UpgradeInstanceRequest, dict]): + request (Union[google.cloud.redis_v1.types.DeleteInstanceRequest, dict]): The request object. Request for - [UpgradeInstance][google.cloud.redis.v1.CloudRedis.UpgradeInstance]. + [DeleteInstance][google.cloud.redis.v1.CloudRedis.DeleteInstance]. name (str): Required. Redis instance resource name using the form: ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` @@ -1339,13 +1231,6 @@ def sample_upgrade_instance(): This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - redis_version (str): - Required. Specifies the target - version of Redis software to upgrade to. - - This corresponds to the ``redis_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1358,575 +1243,38 @@ def sample_upgrade_instance(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be - :class:`google.cloud.redis_v1.types.Instance` A - Memorystore for Redis 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, redis_version]) - if request is 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, cloud_redis.UpgradeInstanceRequest): - request = cloud_redis.UpgradeInstanceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if redis_version is not None: - request.redis_version = redis_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.upgrade_instance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - cloud_redis.Instance, - metadata_type=cloud_redis.OperationMetadata, - ) - - # Done; return the response. - return response - - def import_instance(self, - request: Optional[Union[cloud_redis.ImportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - input_config: Optional[cloud_redis.InputConfig] = 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"""Import a Redis RDB snapshot file from Cloud Storage - into a Redis instance. - Redis may stop serving during this operation. Instance - state will be IMPORTING for entire operation. When - complete, the instance will contain only data from the - imported file. - - The returned operation is automatically deleted after a - few hours, so there is no need to call DeleteOperation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - def sample_import_instance(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - input_config = redis_v1.InputConfig() - input_config.gcs_source.uri = "uri_value" - - request = redis_v1.ImportInstanceRequest( - name="name_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.redis_v1.types.ImportInstanceRequest, dict]): - The request object. Request for - [Import][google.cloud.redis.v1.CloudRedis.ImportInstance]. - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - input_config (google.cloud.redis_v1.types.InputConfig): - Required. Specify data to be - imported. - - This corresponds to the ``input_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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`. + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); - The result type for the operation will be - :class:`google.cloud.redis_v1.types.Instance` A - Memorystore for Redis 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, input_config]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, cloud_redis.ImportInstanceRequest): - request = cloud_redis.ImportInstanceRequest(request) + if not isinstance(request, cloud_redis.DeleteInstanceRequest): + request = cloud_redis.DeleteInstanceRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name - if input_config is not None: - request.input_config = input_config # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_instance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - cloud_redis.Instance, - metadata_type=cloud_redis.OperationMetadata, - ) - - # Done; return the response. - return response - - def export_instance(self, - request: Optional[Union[cloud_redis.ExportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - output_config: Optional[cloud_redis.OutputConfig] = 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"""Export Redis instance data into a Redis RDB format - file in Cloud Storage. - Redis will continue serving during this operation. - - The returned operation is automatically deleted after a - few hours, so there is no need to call DeleteOperation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - def sample_export_instance(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - output_config = redis_v1.OutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = redis_v1.ExportInstanceRequest( - name="name_value", - output_config=output_config, - ) - - # Make the request - operation = client.export_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.redis_v1.types.ExportInstanceRequest, dict]): - The request object. Request for - [Export][google.cloud.redis.v1.CloudRedis.ExportInstance]. - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - output_config (google.cloud.redis_v1.types.OutputConfig): - Required. Specify data to be - exported. - - This corresponds to the ``output_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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.redis_v1.types.Instance` A - Memorystore for Redis 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, output_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, cloud_redis.ExportInstanceRequest): - request = cloud_redis.ExportInstanceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if output_config is not None: - request.output_config = output_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_instance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - cloud_redis.Instance, - metadata_type=cloud_redis.OperationMetadata, - ) - - # Done; return the response. - return response - - def failover_instance(self, - request: Optional[Union[cloud_redis.FailoverInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - data_protection_mode: Optional[cloud_redis.FailoverInstanceRequest.DataProtectionMode] = 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"""Initiates a failover of the primary node to current - replica node for a specific STANDARD tier Cloud - Memorystore for Redis instance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - def sample_failover_instance(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - request = redis_v1.FailoverInstanceRequest( - name="name_value", - ) - - # Make the request - operation = client.failover_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.redis_v1.types.FailoverInstanceRequest, dict]): - The request object. Request for - [Failover][google.cloud.redis.v1.CloudRedis.FailoverInstance]. - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data_protection_mode (google.cloud.redis_v1.types.FailoverInstanceRequest.DataProtectionMode): - Optional. Available data protection modes that the user - can choose. If it's unspecified, data protection mode - will be LIMITED_DATA_LOSS by default. - - This corresponds to the ``data_protection_mode`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.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.redis_v1.types.Instance` A - Memorystore for Redis 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, data_protection_mode]) - if request is 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, cloud_redis.FailoverInstanceRequest): - request = cloud_redis.FailoverInstanceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data_protection_mode is not None: - request.data_protection_mode = data_protection_mode - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.failover_instance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - cloud_redis.Instance, - metadata_type=cloud_redis.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_instance(self, - request: Optional[Union[cloud_redis.DeleteInstanceRequest, 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]]] = (), - ) -> operation.Operation: - r"""Deletes a specific Redis instance. Instance stops - serving and data is deleted. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - def sample_delete_instance(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - request = redis_v1.DeleteInstanceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.redis_v1.types.DeleteInstanceRequest, dict]): - The request object. Request for - [DeleteInstance][google.cloud.redis.v1.CloudRedis.DeleteInstance]. - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, cloud_redis.DeleteInstanceRequest): - request = cloud_redis.DeleteInstanceRequest(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_instance] + rpc = self._transport._wrapped_methods[self._transport.delete_instance] # Certain fields should be provided within the metadata header; # add these here. @@ -1958,149 +1306,6 @@ def sample_delete_instance(): # Done; return the response. return response - def reschedule_maintenance(self, - request: Optional[Union[cloud_redis.RescheduleMaintenanceRequest, dict]] = None, - *, - name: Optional[str] = None, - reschedule_type: Optional[cloud_redis.RescheduleMaintenanceRequest.RescheduleType] = None, - schedule_time: Optional[timestamp_pb2.Timestamp] = 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"""Reschedule maintenance for a given instance in a - given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import redis_v1 - - def sample_reschedule_maintenance(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - request = redis_v1.RescheduleMaintenanceRequest( - name="name_value", - reschedule_type="SPECIFIC_TIME", - ) - - # Make the request - operation = client.reschedule_maintenance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.redis_v1.types.RescheduleMaintenanceRequest, dict]): - The request object. Request for - [RescheduleMaintenance][google.cloud.redis.v1.CloudRedis.RescheduleMaintenance]. - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - reschedule_type (google.cloud.redis_v1.types.RescheduleMaintenanceRequest.RescheduleType): - Required. If reschedule type is SPECIFIC_TIME, must set - up schedule_time as well. - - This corresponds to the ``reschedule_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schedule_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. Timestamp when the maintenance shall be - rescheduled to if reschedule_type=SPECIFIC_TIME, in RFC - 3339 format, for example ``2012-11-15T16:19:00.094Z``. - - This corresponds to the ``schedule_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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.redis_v1.types.Instance` A - Memorystore for Redis 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, reschedule_type, schedule_time]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, cloud_redis.RescheduleMaintenanceRequest): - request = cloud_redis.RescheduleMaintenanceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if reschedule_type is not None: - request.reschedule_type = reschedule_type - if schedule_time is not None: - request.schedule_time = schedule_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.reschedule_maintenance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - cloud_redis.Instance, - metadata_type=cloud_redis.OperationMetadata, - ) - - # Done; return the response. - return response - def __enter__(self) -> "CloudRedisClient": return self diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 57832b4d91..2c311ca2c4 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -132,11 +132,6 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.get_instance_auth_string: gapic_v1.method.wrap_method( - self.get_instance_auth_string, - default_timeout=600.0, - client_info=client_info, - ), self.create_instance: gapic_v1.method.wrap_method( self.create_instance, default_timeout=600.0, @@ -147,36 +142,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.upgrade_instance: gapic_v1.method.wrap_method( - self.upgrade_instance, - default_timeout=600.0, - client_info=client_info, - ), - self.import_instance: gapic_v1.method.wrap_method( - self.import_instance, - default_timeout=600.0, - client_info=client_info, - ), - self.export_instance: gapic_v1.method.wrap_method( - self.export_instance, - default_timeout=600.0, - client_info=client_info, - ), - self.failover_instance: gapic_v1.method.wrap_method( - self.failover_instance, - default_timeout=600.0, - client_info=client_info, - ), self.delete_instance: gapic_v1.method.wrap_method( self.delete_instance, default_timeout=600.0, client_info=client_info, ), - self.reschedule_maintenance: gapic_v1.method.wrap_method( - self.reschedule_maintenance, - default_timeout=None, - client_info=client_info, - ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -246,15 +216,6 @@ def get_instance(self) -> Callable[ ]]: raise NotImplementedError() - @property - def get_instance_auth_string(self) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - Union[ - cloud_redis.InstanceAuthString, - Awaitable[cloud_redis.InstanceAuthString] - ]]: - raise NotImplementedError() - @property def create_instance(self) -> Callable[ [cloud_redis.CreateInstanceRequest], @@ -273,42 +234,6 @@ def update_instance(self) -> Callable[ ]]: raise NotImplementedError() - @property - def upgrade_instance(self) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_instance(self) -> Callable[ - [cloud_redis.ImportInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_instance(self) -> Callable[ - [cloud_redis.ExportInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def failover_instance(self) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - @property def delete_instance(self) -> Callable[ [cloud_redis.DeleteInstanceRequest], @@ -318,15 +243,6 @@ def delete_instance(self) -> Callable[ ]]: raise NotImplementedError() - @property - def reschedule_maintenance(self) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - @property def list_operations( self, diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index 0df3839157..b6a2004d09 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -332,35 +332,6 @@ def get_instance(self) -> Callable[ ) return self._stubs['get_instance'] - @property - def get_instance_auth_string(self) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - cloud_redis.InstanceAuthString]: - r"""Return a callable for the get instance auth string method over gRPC. - - Gets the AUTH string for a Redis instance. If AUTH is - not enabled for the instance the response will be empty. - This information is not included in the details returned - to GetInstance. - - Returns: - Callable[[~.GetInstanceAuthStringRequest], - ~.InstanceAuthString]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_instance_auth_string' not in self._stubs: - self._stubs['get_instance_auth_string'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/GetInstanceAuthString', - request_serializer=cloud_redis.GetInstanceAuthStringRequest.serialize, - response_deserializer=cloud_redis.InstanceAuthString.deserialize, - ) - return self._stubs['get_instance_auth_string'] - @property def create_instance(self) -> Callable[ [cloud_redis.CreateInstanceRequest], @@ -431,126 +402,6 @@ def update_instance(self) -> Callable[ ) return self._stubs['update_instance'] - @property - def upgrade_instance(self) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - operations_pb2.Operation]: - r"""Return a callable for the upgrade instance method over gRPC. - - Upgrades Redis instance to the newer Redis version - specified in the request. - - Returns: - Callable[[~.UpgradeInstanceRequest], - ~.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 'upgrade_instance' not in self._stubs: - self._stubs['upgrade_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/UpgradeInstance', - request_serializer=cloud_redis.UpgradeInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['upgrade_instance'] - - @property - def import_instance(self) -> Callable[ - [cloud_redis.ImportInstanceRequest], - operations_pb2.Operation]: - r"""Return a callable for the import instance method over gRPC. - - Import a Redis RDB snapshot file from Cloud Storage - into a Redis instance. - Redis may stop serving during this operation. Instance - state will be IMPORTING for entire operation. When - complete, the instance will contain only data from the - imported file. - - The returned operation is automatically deleted after a - few hours, so there is no need to call DeleteOperation. - - Returns: - Callable[[~.ImportInstanceRequest], - ~.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 'import_instance' not in self._stubs: - self._stubs['import_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/ImportInstance', - request_serializer=cloud_redis.ImportInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_instance'] - - @property - def export_instance(self) -> Callable[ - [cloud_redis.ExportInstanceRequest], - operations_pb2.Operation]: - r"""Return a callable for the export instance method over gRPC. - - Export Redis instance data into a Redis RDB format - file in Cloud Storage. - Redis will continue serving during this operation. - - The returned operation is automatically deleted after a - few hours, so there is no need to call DeleteOperation. - - Returns: - Callable[[~.ExportInstanceRequest], - ~.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 'export_instance' not in self._stubs: - self._stubs['export_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/ExportInstance', - request_serializer=cloud_redis.ExportInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_instance'] - - @property - def failover_instance(self) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - operations_pb2.Operation]: - r"""Return a callable for the failover instance method over gRPC. - - Initiates a failover of the primary node to current - replica node for a specific STANDARD tier Cloud - Memorystore for Redis instance. - - Returns: - Callable[[~.FailoverInstanceRequest], - ~.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 'failover_instance' not in self._stubs: - self._stubs['failover_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/FailoverInstance', - request_serializer=cloud_redis.FailoverInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['failover_instance'] - @property def delete_instance(self) -> Callable[ [cloud_redis.DeleteInstanceRequest], @@ -578,33 +429,6 @@ def delete_instance(self) -> Callable[ ) return self._stubs['delete_instance'] - @property - def reschedule_maintenance(self) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - operations_pb2.Operation]: - r"""Return a callable for the reschedule maintenance method over gRPC. - - Reschedule maintenance for a given instance in a - given project and location. - - Returns: - Callable[[~.RescheduleMaintenanceRequest], - ~.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 'reschedule_maintenance' not in self._stubs: - self._stubs['reschedule_maintenance'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/RescheduleMaintenance', - request_serializer=cloud_redis.RescheduleMaintenanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['reschedule_maintenance'] - def close(self): self.grpc_channel.close() diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py index 78b7c4d028..444587bafe 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py @@ -338,35 +338,6 @@ def get_instance(self) -> Callable[ ) return self._stubs['get_instance'] - @property - def get_instance_auth_string(self) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - Awaitable[cloud_redis.InstanceAuthString]]: - r"""Return a callable for the get instance auth string method over gRPC. - - Gets the AUTH string for a Redis instance. If AUTH is - not enabled for the instance the response will be empty. - This information is not included in the details returned - to GetInstance. - - Returns: - Callable[[~.GetInstanceAuthStringRequest], - Awaitable[~.InstanceAuthString]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_instance_auth_string' not in self._stubs: - self._stubs['get_instance_auth_string'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/GetInstanceAuthString', - request_serializer=cloud_redis.GetInstanceAuthStringRequest.serialize, - response_deserializer=cloud_redis.InstanceAuthString.deserialize, - ) - return self._stubs['get_instance_auth_string'] - @property def create_instance(self) -> Callable[ [cloud_redis.CreateInstanceRequest], @@ -437,126 +408,6 @@ def update_instance(self) -> Callable[ ) return self._stubs['update_instance'] - @property - def upgrade_instance(self) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the upgrade instance method over gRPC. - - Upgrades Redis instance to the newer Redis version - specified in the request. - - Returns: - Callable[[~.UpgradeInstanceRequest], - 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 'upgrade_instance' not in self._stubs: - self._stubs['upgrade_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/UpgradeInstance', - request_serializer=cloud_redis.UpgradeInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['upgrade_instance'] - - @property - def import_instance(self) -> Callable[ - [cloud_redis.ImportInstanceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import instance method over gRPC. - - Import a Redis RDB snapshot file from Cloud Storage - into a Redis instance. - Redis may stop serving during this operation. Instance - state will be IMPORTING for entire operation. When - complete, the instance will contain only data from the - imported file. - - The returned operation is automatically deleted after a - few hours, so there is no need to call DeleteOperation. - - Returns: - Callable[[~.ImportInstanceRequest], - 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 'import_instance' not in self._stubs: - self._stubs['import_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/ImportInstance', - request_serializer=cloud_redis.ImportInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_instance'] - - @property - def export_instance(self) -> Callable[ - [cloud_redis.ExportInstanceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the export instance method over gRPC. - - Export Redis instance data into a Redis RDB format - file in Cloud Storage. - Redis will continue serving during this operation. - - The returned operation is automatically deleted after a - few hours, so there is no need to call DeleteOperation. - - Returns: - Callable[[~.ExportInstanceRequest], - 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 'export_instance' not in self._stubs: - self._stubs['export_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/ExportInstance', - request_serializer=cloud_redis.ExportInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_instance'] - - @property - def failover_instance(self) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the failover instance method over gRPC. - - Initiates a failover of the primary node to current - replica node for a specific STANDARD tier Cloud - Memorystore for Redis instance. - - Returns: - Callable[[~.FailoverInstanceRequest], - 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 'failover_instance' not in self._stubs: - self._stubs['failover_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/FailoverInstance', - request_serializer=cloud_redis.FailoverInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['failover_instance'] - @property def delete_instance(self) -> Callable[ [cloud_redis.DeleteInstanceRequest], @@ -584,33 +435,6 @@ def delete_instance(self) -> Callable[ ) return self._stubs['delete_instance'] - @property - def reschedule_maintenance(self) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the reschedule maintenance method over gRPC. - - Reschedule maintenance for a given instance in a - given project and location. - - Returns: - Callable[[~.RescheduleMaintenanceRequest], - 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 'reschedule_maintenance' not in self._stubs: - self._stubs['reschedule_maintenance'] = self.grpc_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/RescheduleMaintenance', - request_serializer=cloud_redis.RescheduleMaintenanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['reschedule_maintenance'] - def _prep_wrapped_messages(self, client_info): """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -624,11 +448,6 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.get_instance_auth_string: self._wrap_method( - self.get_instance_auth_string, - default_timeout=600.0, - client_info=client_info, - ), self.create_instance: self._wrap_method( self.create_instance, default_timeout=600.0, @@ -639,36 +458,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.upgrade_instance: self._wrap_method( - self.upgrade_instance, - default_timeout=600.0, - client_info=client_info, - ), - self.import_instance: self._wrap_method( - self.import_instance, - default_timeout=600.0, - client_info=client_info, - ), - self.export_instance: self._wrap_method( - self.export_instance, - default_timeout=600.0, - client_info=client_info, - ), - self.failover_instance: self._wrap_method( - self.failover_instance, - default_timeout=600.0, - client_info=client_info, - ), self.delete_instance: self._wrap_method( self.delete_instance, default_timeout=600.0, client_info=client_info, ), - self.reschedule_maintenance: self._wrap_method( - self.reschedule_maintenance, - default_timeout=None, - client_info=client_info, - ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py index 0d6c45081d..13a03f6e2c 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py @@ -92,22 +92,6 @@ def post_delete_instance(self, response): logging.log(f"Received response: {response}") return response - def pre_export_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_export_instance(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_failover_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_failover_instance(self, response): - logging.log(f"Received response: {response}") - return response - def pre_get_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -116,22 +100,6 @@ def post_get_instance(self, response): logging.log(f"Received response: {response}") return response - def pre_get_instance_auth_string(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_instance_auth_string(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_instance(self, response): - logging.log(f"Received response: {response}") - return response - def pre_list_instances(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -140,14 +108,6 @@ def post_list_instances(self, response): logging.log(f"Received response: {response}") return response - def pre_reschedule_maintenance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_reschedule_maintenance(self, response): - logging.log(f"Received response: {response}") - return response - def pre_update_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -156,14 +116,6 @@ def post_update_instance(self, response): logging.log(f"Received response: {response}") return response - def pre_upgrade_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_upgrade_instance(self, response): - logging.log(f"Received response: {response}") - return response - transport = CloudRedisRestTransport(interceptor=MyCustomCloudRedisInterceptor()) client = CloudRedisClient(transport=transport) @@ -203,40 +155,6 @@ def post_delete_instance(self, response: operations_pb2.Operation) -> operations """ return response - def pre_export_instance(self, request: cloud_redis.ExportInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ExportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for export_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - def post_export_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for export_instance - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - - def pre_failover_instance(self, request: cloud_redis.FailoverInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.FailoverInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for failover_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - def post_failover_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for failover_instance - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - def pre_get_instance(self, request: cloud_redis.GetInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_instance @@ -254,40 +172,6 @@ def post_get_instance(self, response: cloud_redis.Instance) -> cloud_redis.Insta """ return response - def pre_get_instance_auth_string(self, request: cloud_redis.GetInstanceAuthStringRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.GetInstanceAuthStringRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_instance_auth_string - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - def post_get_instance_auth_string(self, response: cloud_redis.InstanceAuthString) -> cloud_redis.InstanceAuthString: - """Post-rpc interceptor for get_instance_auth_string - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - - def pre_import_instance(self, request: cloud_redis.ImportInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ImportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for import_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - def post_import_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_instance - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - def pre_list_instances(self, request: cloud_redis.ListInstancesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_instances @@ -305,23 +189,6 @@ def post_list_instances(self, response: cloud_redis.ListInstancesResponse) -> cl """ return response - def pre_reschedule_maintenance(self, request: cloud_redis.RescheduleMaintenanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.RescheduleMaintenanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for reschedule_maintenance - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - def post_reschedule_maintenance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for reschedule_maintenance - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - def pre_update_instance(self, request: cloud_redis.UpdateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_instance @@ -339,23 +206,6 @@ def post_update_instance(self, response: operations_pb2.Operation) -> operations """ return response - def pre_upgrade_instance(self, request: cloud_redis.UpgradeInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.UpgradeInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for upgrade_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - def post_upgrade_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for upgrade_instance - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - def pre_get_location( self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: @@ -910,9 +760,9 @@ def __call__(self, ) return resp - class _ExportInstance(_BaseCloudRedisRestTransport._BaseExportInstance, CloudRedisRestStub): + class _GetInstance(_BaseCloudRedisRestTransport._BaseGetInstance, CloudRedisRestStub): def __hash__(self): - return hash("CloudRedisRestTransport.ExportInstance") + return hash("CloudRedisRestTransport.GetInstance") @staticmethod def _get_response( @@ -933,22 +783,21 @@ 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: cloud_redis.ExportInstanceRequest, *, + request: cloud_redis.GetInstanceRequest, *, retry: OptionalRetry=gapic_v1.method.DEFAULT, timeout: Optional[float]=None, metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the export instance method over HTTP. + ) -> cloud_redis.Instance: + r"""Call the get instance method over HTTP. Args: - request (~.cloud_redis.ExportInstanceRequest): + request (~.cloud_redis.GetInstanceRequest): The request object. Request for - [Export][google.cloud.redis.v1.CloudRedis.ExportInstance]. + [GetInstance][google.cloud.redis.v1.CloudRedis.GetInstance]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -958,28 +807,23 @@ def __call__(self, be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - + ~.cloud_redis.Instance: + A Memorystore for Redis instance. """ - http_options = _BaseCloudRedisRestTransport._BaseExportInstance._get_http_options() - - request, metadata = self._interceptor.pre_export_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseExportInstance._get_transcoded_request(http_options, request) + http_options = _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() - body = _BaseCloudRedisRestTransport._BaseExportInstance._get_request_body_json(transcoded_request) + request, metadata = self._interceptor.pre_get_instance(request, metadata) + transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseExportInstance._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._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 = json_format.MessageToJson(request) + request_payload = type(request).to_json(request) except: request_payload = None http_request = { @@ -989,17 +833,17 @@ def __call__(self, "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.redis_v1.CloudRedisClient.ExportInstance", + f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetInstance", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ExportInstance", + "rpcName": "GetInstance", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = CloudRedisRestTransport._ExportInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._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. @@ -1007,13 +851,15 @@ def __call__(self, 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 = cloud_redis.Instance() + pb_resp = cloud_redis.Instance.pb(resp) - resp = self._interceptor.post_export_instance(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_instance(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = cloud_redis.Instance.to_json(response) except: response_payload = None http_response = { @@ -1022,19 +868,19 @@ def __call__(self, "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisClient.export_instance", + "Received response for google.cloud.redis_v1.CloudRedisClient.get_instance", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ExportInstance", + "rpcName": "GetInstance", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FailoverInstance(_BaseCloudRedisRestTransport._BaseFailoverInstance, CloudRedisRestStub): + class _ListInstances(_BaseCloudRedisRestTransport._BaseListInstances, CloudRedisRestStub): def __hash__(self): - return hash("CloudRedisRestTransport.FailoverInstance") + return hash("CloudRedisRestTransport.ListInstances") @staticmethod def _get_response( @@ -1055,22 +901,21 @@ 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: cloud_redis.FailoverInstanceRequest, *, + request: cloud_redis.ListInstancesRequest, *, retry: OptionalRetry=gapic_v1.method.DEFAULT, timeout: Optional[float]=None, metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the failover instance method over HTTP. + ) -> cloud_redis.ListInstancesResponse: + r"""Call the list instances method over HTTP. Args: - request (~.cloud_redis.FailoverInstanceRequest): + request (~.cloud_redis.ListInstancesRequest): The request object. Request for - [Failover][google.cloud.redis.v1.CloudRedis.FailoverInstance]. + [ListInstances][google.cloud.redis.v1.CloudRedis.ListInstances]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1080,28 +925,25 @@ def __call__(self, be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + ~.cloud_redis.ListInstancesResponse: + Response for + [ListInstances][google.cloud.redis.v1.CloudRedis.ListInstances]. """ - http_options = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_http_options() - - request, metadata = self._interceptor.pre_failover_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_transcoded_request(http_options, request) + http_options = _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() - body = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_request_body_json(transcoded_request) + request, metadata = self._interceptor.pre_list_instances(request, metadata) + transcoded_request = _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseListInstances._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) + request_payload = type(request).to_json(request) except: request_payload = None http_request = { @@ -1111,17 +953,17 @@ def __call__(self, "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.redis_v1.CloudRedisClient.FailoverInstance", + f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListInstances", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "FailoverInstance", + "rpcName": "ListInstances", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = CloudRedisRestTransport._FailoverInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._ListInstances._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1129,13 +971,15 @@ def __call__(self, 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 = cloud_redis.ListInstancesResponse() + pb_resp = cloud_redis.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_failover_instance(resp) + resp = self._interceptor.post_list_instances(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = cloud_redis.ListInstancesResponse.to_json(response) except: response_payload = None http_response = { @@ -1144,19 +988,19 @@ def __call__(self, "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisClient.failover_instance", + "Received response for google.cloud.redis_v1.CloudRedisClient.list_instances", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "FailoverInstance", + "rpcName": "ListInstances", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetInstance(_BaseCloudRedisRestTransport._BaseGetInstance, CloudRedisRestStub): + class _UpdateInstance(_BaseCloudRedisRestTransport._BaseUpdateInstance, CloudRedisRestStub): def __hash__(self): - return hash("CloudRedisRestTransport.GetInstance") + return hash("CloudRedisRestTransport.UpdateInstance") @staticmethod def _get_response( @@ -1177,21 +1021,22 @@ 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: cloud_redis.GetInstanceRequest, *, + request: cloud_redis.UpdateInstanceRequest, *, retry: OptionalRetry=gapic_v1.method.DEFAULT, timeout: Optional[float]=None, metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.Instance: - r"""Call the get instance method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update instance method over HTTP. Args: - request (~.cloud_redis.GetInstanceRequest): + request (~.cloud_redis.UpdateInstanceRequest): The request object. Request for - [GetInstance][google.cloud.redis.v1.CloudRedis.GetInstance]. + [UpdateInstance][google.cloud.redis.v1.CloudRedis.UpdateInstance]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1201,23 +1046,28 @@ def __call__(self, be of type `bytes`. Returns: - ~.cloud_redis.Instance: - A Memorystore for Redis instance. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + """ - http_options = _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + http_options = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() - request, metadata = self._interceptor.pre_get_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_instance(request, metadata) + transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request(http_options, request) + + body = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseUpdateInstance._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) + request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { @@ -1227,17 +1077,17 @@ def __call__(self, "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetInstance", + f"Sending request for google.cloud.redis_v1.CloudRedisClient.UpdateInstance", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "GetInstance", + "rpcName": "UpdateInstance", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = CloudRedisRestTransport._GetInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._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 # subclass. @@ -1245,15 +1095,13 @@ def __call__(self, raise core_exceptions.from_http_response(response) # Return the response - resp = cloud_redis.Instance() - pb_resp = cloud_redis.Instance.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_instance(resp) + resp = self._interceptor.post_update_instance(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = cloud_redis.Instance.to_json(response) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1262,749 +1110,23 @@ def __call__(self, "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisClient.get_instance", + "Received response for google.cloud.redis_v1.CloudRedisClient.update_instance", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "GetInstance", + "rpcName": "UpdateInstance", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetInstanceAuthString(_BaseCloudRedisRestTransport._BaseGetInstanceAuthString, CloudRedisRestStub): - def __hash__(self): - return hash("CloudRedisRestTransport.GetInstanceAuthString") - - @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: cloud_redis.GetInstanceAuthStringRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.InstanceAuthString: - r"""Call the get instance auth string method over HTTP. - - Args: - request (~.cloud_redis.GetInstanceAuthStringRequest): - The request object. Request for - [GetInstanceAuthString][google.cloud.redis.v1.CloudRedis.GetInstanceAuthString]. - retry (google.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: - ~.cloud_redis.InstanceAuthString: - Instance AUTH string details. - """ - - http_options = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_http_options() - - request, metadata = self._interceptor.pre_get_instance_auth_string(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._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.cloud.redis_v1.CloudRedisClient.GetInstanceAuthString", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "GetInstanceAuthString", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = CloudRedisRestTransport._GetInstanceAuthString._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 = cloud_redis.InstanceAuthString() - pb_resp = cloud_redis.InstanceAuthString.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_instance_auth_string(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = cloud_redis.InstanceAuthString.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.cloud.redis_v1.CloudRedisClient.get_instance_auth_string", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "GetInstanceAuthString", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ImportInstance(_BaseCloudRedisRestTransport._BaseImportInstance, CloudRedisRestStub): - def __hash__(self): - return hash("CloudRedisRestTransport.ImportInstance") - - @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: cloud_redis.ImportInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the import instance method over HTTP. - - Args: - request (~.cloud_redis.ImportInstanceRequest): - The request object. Request for - [Import][google.cloud.redis.v1.CloudRedis.ImportInstance]. - retry (google.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 = _BaseCloudRedisRestTransport._BaseImportInstance._get_http_options() - - request, metadata = self._interceptor.pre_import_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseImportInstance._get_transcoded_request(http_options, request) - - body = _BaseCloudRedisRestTransport._BaseImportInstance._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseImportInstance._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.cloud.redis_v1.CloudRedisClient.ImportInstance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ImportInstance", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = CloudRedisRestTransport._ImportInstance._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_import_instance(resp) - 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.cloud.redis_v1.CloudRedisClient.import_instance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ImportInstance", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListInstances(_BaseCloudRedisRestTransport._BaseListInstances, CloudRedisRestStub): - def __hash__(self): - return hash("CloudRedisRestTransport.ListInstances") - - @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: cloud_redis.ListInstancesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.ListInstancesResponse: - r"""Call the list instances method over HTTP. - - Args: - request (~.cloud_redis.ListInstancesRequest): - The request object. Request for - [ListInstances][google.cloud.redis.v1.CloudRedis.ListInstances]. - retry (google.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: - ~.cloud_redis.ListInstancesResponse: - Response for - [ListInstances][google.cloud.redis.v1.CloudRedis.ListInstances]. - - """ - - http_options = _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() - - request, metadata = self._interceptor.pre_list_instances(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListInstances._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.cloud.redis_v1.CloudRedisClient.ListInstances", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ListInstances", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = CloudRedisRestTransport._ListInstances._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 = cloud_redis.ListInstancesResponse() - pb_resp = cloud_redis.ListInstancesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_instances(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = cloud_redis.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.cloud.redis_v1.CloudRedisClient.list_instances", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ListInstances", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _RescheduleMaintenance(_BaseCloudRedisRestTransport._BaseRescheduleMaintenance, CloudRedisRestStub): - def __hash__(self): - return hash("CloudRedisRestTransport.RescheduleMaintenance") - - @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: cloud_redis.RescheduleMaintenanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the reschedule maintenance method over HTTP. - - Args: - request (~.cloud_redis.RescheduleMaintenanceRequest): - The request object. Request for - [RescheduleMaintenance][google.cloud.redis.v1.CloudRedis.RescheduleMaintenance]. - retry (google.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 = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_http_options() - - request, metadata = self._interceptor.pre_reschedule_maintenance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_transcoded_request(http_options, request) - - body = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._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.cloud.redis_v1.CloudRedisClient.RescheduleMaintenance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "RescheduleMaintenance", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = CloudRedisRestTransport._RescheduleMaintenance._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_reschedule_maintenance(resp) - 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.cloud.redis_v1.CloudRedisClient.reschedule_maintenance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "RescheduleMaintenance", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateInstance(_BaseCloudRedisRestTransport._BaseUpdateInstance, CloudRedisRestStub): - def __hash__(self): - return hash("CloudRedisRestTransport.UpdateInstance") - - @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: cloud_redis.UpdateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update instance method over HTTP. - - Args: - request (~.cloud_redis.UpdateInstanceRequest): - The request object. Request for - [UpdateInstance][google.cloud.redis.v1.CloudRedis.UpdateInstance]. - retry (google.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 = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() - - request, metadata = self._interceptor.pre_update_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request(http_options, request) - - body = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseUpdateInstance._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.cloud.redis_v1.CloudRedisClient.UpdateInstance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "UpdateInstance", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = CloudRedisRestTransport._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 - # 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_instance(resp) - 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.cloud.redis_v1.CloudRedisClient.update_instance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "UpdateInstance", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpgradeInstance(_BaseCloudRedisRestTransport._BaseUpgradeInstance, CloudRedisRestStub): - def __hash__(self): - return hash("CloudRedisRestTransport.UpgradeInstance") - - @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: cloud_redis.UpgradeInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the upgrade instance method over HTTP. - - Args: - request (~.cloud_redis.UpgradeInstanceRequest): - The request object. Request for - [UpgradeInstance][google.cloud.redis.v1.CloudRedis.UpgradeInstance]. - retry (google.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 = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_http_options() - - request, metadata = self._interceptor.pre_upgrade_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_transcoded_request(http_options, request) - - body = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseUpgradeInstance._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.cloud.redis_v1.CloudRedisClient.UpgradeInstance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "UpgradeInstance", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = CloudRedisRestTransport._UpgradeInstance._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_upgrade_instance(resp) - 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.cloud.redis_v1.CloudRedisClient.upgrade_instance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "UpgradeInstance", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - 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._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def create_instance(self) -> Callable[ + [cloud_redis.CreateInstanceRequest], + 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._CreateInstance(self._session, self._host, self._interceptor) # type: ignore @property def delete_instance(self) -> Callable[ @@ -2014,22 +1136,6 @@ def delete_instance(self) -> Callable[ # In C++ this would require a dynamic_cast return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore - @property - def export_instance(self) -> Callable[ - [cloud_redis.ExportInstanceRequest], - 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._ExportInstance(self._session, self._host, self._interceptor) # type: ignore - - @property - def failover_instance(self) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - 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._FailoverInstance(self._session, self._host, self._interceptor) # type: ignore - @property def get_instance(self) -> Callable[ [cloud_redis.GetInstanceRequest], @@ -2038,22 +1144,6 @@ def get_instance(self) -> Callable[ # In C++ this would require a dynamic_cast return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore - @property - def get_instance_auth_string(self) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - cloud_redis.InstanceAuthString]: - # 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._GetInstanceAuthString(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_instance(self) -> Callable[ - [cloud_redis.ImportInstanceRequest], - 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._ImportInstance(self._session, self._host, self._interceptor) # type: ignore - @property def list_instances(self) -> Callable[ [cloud_redis.ListInstancesRequest], @@ -2062,14 +1152,6 @@ def list_instances(self) -> Callable[ # In C++ this would require a dynamic_cast return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore - @property - def reschedule_maintenance(self) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - 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._RescheduleMaintenance(self._session, self._host, self._interceptor) # type: ignore - @property def update_instance(self) -> Callable[ [cloud_redis.UpdateInstanceRequest], @@ -2078,14 +1160,6 @@ def update_instance(self) -> Callable[ # In C++ this would require a dynamic_cast return self._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore - @property - def upgrade_instance(self) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - 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._UpgradeInstance(self._session, self._host, self._interceptor) # type: ignore - @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py index 9ce8542f78..26e787e580 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py @@ -105,22 +105,6 @@ async def post_delete_instance(self, response): logging.log(f"Received response: {response}") return response - async def pre_export_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - async def post_export_instance(self, response): - logging.log(f"Received response: {response}") - return response - - async def pre_failover_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - async def post_failover_instance(self, response): - logging.log(f"Received response: {response}") - return response - async def pre_get_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -129,22 +113,6 @@ async def post_get_instance(self, response): logging.log(f"Received response: {response}") return response - async def pre_get_instance_auth_string(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - async def post_get_instance_auth_string(self, response): - logging.log(f"Received response: {response}") - return response - - async def pre_import_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - async def post_import_instance(self, response): - logging.log(f"Received response: {response}") - return response - async def pre_list_instances(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -153,14 +121,6 @@ async def post_list_instances(self, response): logging.log(f"Received response: {response}") return response - async def pre_reschedule_maintenance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - async def post_reschedule_maintenance(self, response): - logging.log(f"Received response: {response}") - return response - async def pre_update_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -169,14 +129,6 @@ async def post_update_instance(self, response): logging.log(f"Received response: {response}") return response - async def pre_upgrade_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - async def post_upgrade_instance(self, response): - logging.log(f"Received response: {response}") - return response - transport = AsyncCloudRedisRestTransport(interceptor=MyCustomCloudRedisInterceptor()) client = async CloudRedisClient(transport=transport) @@ -216,40 +168,6 @@ async def post_delete_instance(self, response: operations_pb2.Operation) -> oper """ return response - async def pre_export_instance(self, request: cloud_redis.ExportInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ExportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for export_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - async def post_export_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for export_instance - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - - async def pre_failover_instance(self, request: cloud_redis.FailoverInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.FailoverInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for failover_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - async def post_failover_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for failover_instance - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - async def pre_get_instance(self, request: cloud_redis.GetInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_instance @@ -267,40 +185,6 @@ async def post_get_instance(self, response: cloud_redis.Instance) -> cloud_redis """ return response - async def pre_get_instance_auth_string(self, request: cloud_redis.GetInstanceAuthStringRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.GetInstanceAuthStringRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_instance_auth_string - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - async def post_get_instance_auth_string(self, response: cloud_redis.InstanceAuthString) -> cloud_redis.InstanceAuthString: - """Post-rpc interceptor for get_instance_auth_string - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - - async def pre_import_instance(self, request: cloud_redis.ImportInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ImportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for import_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - async def post_import_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_instance - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - async def pre_list_instances(self, request: cloud_redis.ListInstancesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_instances @@ -318,23 +202,6 @@ async def post_list_instances(self, response: cloud_redis.ListInstancesResponse) """ return response - async def pre_reschedule_maintenance(self, request: cloud_redis.RescheduleMaintenanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.RescheduleMaintenanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for reschedule_maintenance - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - async def post_reschedule_maintenance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for reschedule_maintenance - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - async def pre_update_instance(self, request: cloud_redis.UpdateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_instance @@ -352,23 +219,6 @@ async def post_update_instance(self, response: operations_pb2.Operation) -> oper """ return response - async def pre_upgrade_instance(self, request: cloud_redis.UpgradeInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.UpgradeInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for upgrade_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudRedis server. - """ - return request, metadata - - async def post_upgrade_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for upgrade_instance - - Override in a subclass to manipulate the response - after it is returned by the CloudRedis server but before - it is returned to user code. - """ - return response - async def pre_get_location( self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: @@ -613,11 +463,6 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.get_instance_auth_string: self._wrap_method( - self.get_instance_auth_string, - default_timeout=600.0, - client_info=client_info, - ), self.create_instance: self._wrap_method( self.create_instance, default_timeout=600.0, @@ -628,36 +473,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.upgrade_instance: self._wrap_method( - self.upgrade_instance, - default_timeout=600.0, - client_info=client_info, - ), - self.import_instance: self._wrap_method( - self.import_instance, - default_timeout=600.0, - client_info=client_info, - ), - self.export_instance: self._wrap_method( - self.export_instance, - default_timeout=600.0, - client_info=client_info, - ), - self.failover_instance: self._wrap_method( - self.failover_instance, - default_timeout=600.0, - client_info=client_info, - ), self.delete_instance: self._wrap_method( self.delete_instance, default_timeout=600.0, client_info=client_info, ), - self.reschedule_maintenance: self._wrap_method( - self.reschedule_maintenance, - default_timeout=None, - client_info=client_info, - ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, @@ -953,9 +773,9 @@ async def __call__(self, return resp - class _ExportInstance(_BaseCloudRedisRestTransport._BaseExportInstance, AsyncCloudRedisRestStub): + class _GetInstance(_BaseCloudRedisRestTransport._BaseGetInstance, AsyncCloudRedisRestStub): def __hash__(self): - return hash("AsyncCloudRedisRestTransport.ExportInstance") + return hash("AsyncCloudRedisRestTransport.GetInstance") @staticmethod async def _get_response( @@ -976,22 +796,21 @@ async def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response async def __call__(self, - request: cloud_redis.ExportInstanceRequest, *, + request: cloud_redis.GetInstanceRequest, *, retry: OptionalRetry=gapic_v1.method.DEFAULT, timeout: Optional[float]=None, metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the export instance method over HTTP. + ) -> cloud_redis.Instance: + r"""Call the get instance method over HTTP. Args: - request (~.cloud_redis.ExportInstanceRequest): + request (~.cloud_redis.GetInstanceRequest): The request object. Request for - [Export][google.cloud.redis.v1.CloudRedis.ExportInstance]. + [GetInstance][google.cloud.redis.v1.CloudRedis.GetInstance]. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1001,28 +820,23 @@ async def __call__(self, be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - + ~.cloud_redis.Instance: + A Memorystore for Redis instance. """ - http_options = _BaseCloudRedisRestTransport._BaseExportInstance._get_http_options() - - request, metadata = await self._interceptor.pre_export_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseExportInstance._get_transcoded_request(http_options, request) + http_options = _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() - body = _BaseCloudRedisRestTransport._BaseExportInstance._get_request_body_json(transcoded_request) + request, metadata = await self._interceptor.pre_get_instance(request, metadata) + transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseExportInstance._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._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 = json_format.MessageToJson(request) + request_payload = type(request).to_json(request) except: request_payload = None http_request = { @@ -1032,17 +846,17 @@ async def __call__(self, "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.redis_v1.CloudRedisClient.ExportInstance", + f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetInstance", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ExportInstance", + "rpcName": "GetInstance", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = await AsyncCloudRedisRestTransport._ExportInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = await AsyncCloudRedisRestTransport._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. @@ -1054,14 +868,14 @@ async def __call__(self, raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response - resp = operations_pb2.Operation() - pb_resp = resp + resp = cloud_redis.Instance() + pb_resp = cloud_redis.Instance.pb(resp) content = await response.read() json_format.Parse(content, pb_resp, ignore_unknown_fields=True) - resp = await self._interceptor.post_export_instance(resp) + resp = await self._interceptor.post_get_instance(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = cloud_redis.Instance.to_json(response) except: response_payload = None http_response = { @@ -1070,10 +884,10 @@ async def __call__(self, "status": "OK", # need to obtain this properly } _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.export_instance", + "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.get_instance", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ExportInstance", + "rpcName": "GetInstance", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -1081,9 +895,9 @@ async def __call__(self, return resp - class _FailoverInstance(_BaseCloudRedisRestTransport._BaseFailoverInstance, AsyncCloudRedisRestStub): + class _ListInstances(_BaseCloudRedisRestTransport._BaseListInstances, AsyncCloudRedisRestStub): def __hash__(self): - return hash("AsyncCloudRedisRestTransport.FailoverInstance") + return hash("AsyncCloudRedisRestTransport.ListInstances") @staticmethod async def _get_response( @@ -1104,22 +918,21 @@ async def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response async def __call__(self, - request: cloud_redis.FailoverInstanceRequest, *, + request: cloud_redis.ListInstancesRequest, *, retry: OptionalRetry=gapic_v1.method.DEFAULT, timeout: Optional[float]=None, metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the failover instance method over HTTP. + ) -> cloud_redis.ListInstancesResponse: + r"""Call the list instances method over HTTP. Args: - request (~.cloud_redis.FailoverInstanceRequest): + request (~.cloud_redis.ListInstancesRequest): The request object. Request for - [Failover][google.cloud.redis.v1.CloudRedis.FailoverInstance]. + [ListInstances][google.cloud.redis.v1.CloudRedis.ListInstances]. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1129,28 +942,25 @@ async def __call__(self, be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + ~.cloud_redis.ListInstancesResponse: + Response for + [ListInstances][google.cloud.redis.v1.CloudRedis.ListInstances]. """ - http_options = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_http_options() - - request, metadata = await self._interceptor.pre_failover_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_transcoded_request(http_options, request) + http_options = _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() - body = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_request_body_json(transcoded_request) + request, metadata = await self._interceptor.pre_list_instances(request, metadata) + transcoded_request = _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseListInstances._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) + request_payload = type(request).to_json(request) except: request_payload = None http_request = { @@ -1160,17 +970,17 @@ async def __call__(self, "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.redis_v1.CloudRedisClient.FailoverInstance", + f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListInstances", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "FailoverInstance", + "rpcName": "ListInstances", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = await AsyncCloudRedisRestTransport._FailoverInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = await AsyncCloudRedisRestTransport._ListInstances._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1182,14 +992,14 @@ async def __call__(self, raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response - resp = operations_pb2.Operation() - pb_resp = resp + resp = cloud_redis.ListInstancesResponse() + pb_resp = cloud_redis.ListInstancesResponse.pb(resp) content = await response.read() json_format.Parse(content, pb_resp, ignore_unknown_fields=True) - resp = await self._interceptor.post_failover_instance(resp) + resp = await self._interceptor.post_list_instances(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = cloud_redis.ListInstancesResponse.to_json(response) except: response_payload = None http_response = { @@ -1198,10 +1008,10 @@ async def __call__(self, "status": "OK", # need to obtain this properly } _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.failover_instance", + "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.list_instances", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "FailoverInstance", + "rpcName": "ListInstances", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -1209,9 +1019,9 @@ async def __call__(self, return resp - class _GetInstance(_BaseCloudRedisRestTransport._BaseGetInstance, AsyncCloudRedisRestStub): + class _UpdateInstance(_BaseCloudRedisRestTransport._BaseUpdateInstance, AsyncCloudRedisRestStub): def __hash__(self): - return hash("AsyncCloudRedisRestTransport.GetInstance") + return hash("AsyncCloudRedisRestTransport.UpdateInstance") @staticmethod async def _get_response( @@ -1232,21 +1042,22 @@ async def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response async def __call__(self, - request: cloud_redis.GetInstanceRequest, *, + request: cloud_redis.UpdateInstanceRequest, *, retry: OptionalRetry=gapic_v1.method.DEFAULT, timeout: Optional[float]=None, metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.Instance: - r"""Call the get instance method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update instance method over HTTP. Args: - request (~.cloud_redis.GetInstanceRequest): + request (~.cloud_redis.UpdateInstanceRequest): The request object. Request for - [GetInstance][google.cloud.redis.v1.CloudRedis.GetInstance]. + [UpdateInstance][google.cloud.redis.v1.CloudRedis.UpdateInstance]. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1256,23 +1067,28 @@ async def __call__(self, be of type `bytes`. Returns: - ~.cloud_redis.Instance: - A Memorystore for Redis instance. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + """ - http_options = _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + http_options = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() - request, metadata = await self._interceptor.pre_get_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_update_instance(request, metadata) + transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request(http_options, request) + + body = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseUpdateInstance._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) + request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { @@ -1282,17 +1098,17 @@ async def __call__(self, "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetInstance", + f"Sending request for google.cloud.redis_v1.CloudRedisClient.UpdateInstance", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "GetInstance", + "rpcName": "UpdateInstance", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = await AsyncCloudRedisRestTransport._GetInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._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 # subclass. @@ -1304,14 +1120,14 @@ async def __call__(self, raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response - resp = cloud_redis.Instance() - pb_resp = cloud_redis.Instance.pb(resp) + resp = operations_pb2.Operation() + pb_resp = resp content = await response.read() json_format.Parse(content, pb_resp, ignore_unknown_fields=True) - resp = await self._interceptor.post_get_instance(resp) + resp = await self._interceptor.post_update_instance(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = cloud_redis.Instance.to_json(response) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1320,768 +1136,10 @@ async def __call__(self, "status": "OK", # need to obtain this properly } _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.get_instance", + "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.update_instance", extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "GetInstance", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - - return resp - - class _GetInstanceAuthString(_BaseCloudRedisRestTransport._BaseGetInstanceAuthString, AsyncCloudRedisRestStub): - def __hash__(self): - return hash("AsyncCloudRedisRestTransport.GetInstanceAuthString") - - @staticmethod - async 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 = await 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 - - async def __call__(self, - request: cloud_redis.GetInstanceAuthStringRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.InstanceAuthString: - r"""Call the get instance auth string method over HTTP. - - Args: - request (~.cloud_redis.GetInstanceAuthStringRequest): - The request object. Request for - [GetInstanceAuthString][google.cloud.redis.v1.CloudRedis.GetInstanceAuthString]. - 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: - ~.cloud_redis.InstanceAuthString: - Instance AUTH string details. - """ - - http_options = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_http_options() - - request, metadata = await self._interceptor.pre_get_instance_auth_string(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._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.cloud.redis_v1.CloudRedisClient.GetInstanceAuthString", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "GetInstanceAuthString", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = await AsyncCloudRedisRestTransport._GetInstanceAuthString._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: - content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore - - # Return the response - resp = cloud_redis.InstanceAuthString() - pb_resp = cloud_redis.InstanceAuthString.pb(resp) - content = await response.read() - json_format.Parse(content, pb_resp, ignore_unknown_fields=True) - resp = await self._interceptor.post_get_instance_auth_string(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = cloud_redis.InstanceAuthString.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly - } - _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.get_instance_auth_string", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "GetInstanceAuthString", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - - return resp - - class _ImportInstance(_BaseCloudRedisRestTransport._BaseImportInstance, AsyncCloudRedisRestStub): - def __hash__(self): - return hash("AsyncCloudRedisRestTransport.ImportInstance") - - @staticmethod - async 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 = await 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 - - async def __call__(self, - request: cloud_redis.ImportInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the import instance method over HTTP. - - Args: - request (~.cloud_redis.ImportInstanceRequest): - The request object. Request for - [Import][google.cloud.redis.v1.CloudRedis.ImportInstance]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseCloudRedisRestTransport._BaseImportInstance._get_http_options() - - request, metadata = await self._interceptor.pre_import_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseImportInstance._get_transcoded_request(http_options, request) - - body = _BaseCloudRedisRestTransport._BaseImportInstance._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseImportInstance._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.cloud.redis_v1.CloudRedisClient.ImportInstance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ImportInstance", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = await AsyncCloudRedisRestTransport._ImportInstance._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: - content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore - - # Return the response - resp = operations_pb2.Operation() - pb_resp = resp - content = await response.read() - json_format.Parse(content, pb_resp, ignore_unknown_fields=True) - resp = await self._interceptor.post_import_instance(resp) - 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": "OK", # need to obtain this properly - } - _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.import_instance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ImportInstance", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - - return resp - - class _ListInstances(_BaseCloudRedisRestTransport._BaseListInstances, AsyncCloudRedisRestStub): - def __hash__(self): - return hash("AsyncCloudRedisRestTransport.ListInstances") - - @staticmethod - async 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 = await 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 - - async def __call__(self, - request: cloud_redis.ListInstancesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.ListInstancesResponse: - r"""Call the list instances method over HTTP. - - Args: - request (~.cloud_redis.ListInstancesRequest): - The request object. Request for - [ListInstances][google.cloud.redis.v1.CloudRedis.ListInstances]. - 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: - ~.cloud_redis.ListInstancesResponse: - Response for - [ListInstances][google.cloud.redis.v1.CloudRedis.ListInstances]. - - """ - - http_options = _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() - - request, metadata = await self._interceptor.pre_list_instances(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListInstances._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.cloud.redis_v1.CloudRedisClient.ListInstances", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ListInstances", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = await AsyncCloudRedisRestTransport._ListInstances._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: - content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore - - # Return the response - resp = cloud_redis.ListInstancesResponse() - pb_resp = cloud_redis.ListInstancesResponse.pb(resp) - content = await response.read() - json_format.Parse(content, pb_resp, ignore_unknown_fields=True) - resp = await self._interceptor.post_list_instances(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = cloud_redis.ListInstancesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly - } - _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.list_instances", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "ListInstances", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - - return resp - - class _RescheduleMaintenance(_BaseCloudRedisRestTransport._BaseRescheduleMaintenance, AsyncCloudRedisRestStub): - def __hash__(self): - return hash("AsyncCloudRedisRestTransport.RescheduleMaintenance") - - @staticmethod - async 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 = await 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 - - async def __call__(self, - request: cloud_redis.RescheduleMaintenanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the reschedule maintenance method over HTTP. - - Args: - request (~.cloud_redis.RescheduleMaintenanceRequest): - The request object. Request for - [RescheduleMaintenance][google.cloud.redis.v1.CloudRedis.RescheduleMaintenance]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_http_options() - - request, metadata = await self._interceptor.pre_reschedule_maintenance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_transcoded_request(http_options, request) - - body = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._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.cloud.redis_v1.CloudRedisClient.RescheduleMaintenance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "RescheduleMaintenance", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = await AsyncCloudRedisRestTransport._RescheduleMaintenance._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: - content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore - - # Return the response - resp = operations_pb2.Operation() - pb_resp = resp - content = await response.read() - json_format.Parse(content, pb_resp, ignore_unknown_fields=True) - resp = await self._interceptor.post_reschedule_maintenance(resp) - 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": "OK", # need to obtain this properly - } - _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.reschedule_maintenance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "RescheduleMaintenance", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - - return resp - - class _UpdateInstance(_BaseCloudRedisRestTransport._BaseUpdateInstance, AsyncCloudRedisRestStub): - def __hash__(self): - return hash("AsyncCloudRedisRestTransport.UpdateInstance") - - @staticmethod - async 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 = await 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 - - async def __call__(self, - request: cloud_redis.UpdateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update instance method over HTTP. - - Args: - request (~.cloud_redis.UpdateInstanceRequest): - The request object. Request for - [UpdateInstance][google.cloud.redis.v1.CloudRedis.UpdateInstance]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() - - request, metadata = await self._interceptor.pre_update_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request(http_options, request) - - body = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseUpdateInstance._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.cloud.redis_v1.CloudRedisClient.UpdateInstance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "UpdateInstance", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = await AsyncCloudRedisRestTransport._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 - # subclass. - if response.status_code >= 400: - content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore - - # Return the response - resp = operations_pb2.Operation() - pb_resp = resp - content = await response.read() - json_format.Parse(content, pb_resp, ignore_unknown_fields=True) - resp = await self._interceptor.post_update_instance(resp) - 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": "OK", # need to obtain this properly - } - _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.update_instance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "UpdateInstance", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - - return resp - - class _UpgradeInstance(_BaseCloudRedisRestTransport._BaseUpgradeInstance, AsyncCloudRedisRestStub): - def __hash__(self): - return hash("AsyncCloudRedisRestTransport.UpgradeInstance") - - @staticmethod - async 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 = await 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 - - async def __call__(self, - request: cloud_redis.UpgradeInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the upgrade instance method over HTTP. - - Args: - request (~.cloud_redis.UpgradeInstanceRequest): - The request object. Request for - [UpgradeInstance][google.cloud.redis.v1.CloudRedis.UpgradeInstance]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_http_options() - - request, metadata = await self._interceptor.pre_upgrade_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_transcoded_request(http_options, request) - - body = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseUpgradeInstance._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.cloud.redis_v1.CloudRedisClient.UpgradeInstance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "UpgradeInstance", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = await AsyncCloudRedisRestTransport._UpgradeInstance._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: - content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore - - # Return the response - resp = operations_pb2.Operation() - pb_resp = resp - content = await response.read() - json_format.Parse(content, pb_resp, ignore_unknown_fields=True) - resp = await self._interceptor.post_upgrade_instance(resp) - 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": "OK", # need to obtain this properly - } - _LOGGER.debug( - "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.upgrade_instance", - extra = { - "serviceName": "google.cloud.redis.v1.CloudRedis", - "rpcName": "UpgradeInstance", + "rpcName": "UpdateInstance", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -2157,60 +1215,24 @@ def delete_instance(self) -> Callable[ operations_pb2.Operation]: return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore - @property - def export_instance(self) -> Callable[ - [cloud_redis.ExportInstanceRequest], - operations_pb2.Operation]: - return self._ExportInstance(self._session, self._host, self._interceptor) # type: ignore - - @property - def failover_instance(self) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - operations_pb2.Operation]: - return self._FailoverInstance(self._session, self._host, self._interceptor) # type: ignore - @property def get_instance(self) -> Callable[ [cloud_redis.GetInstanceRequest], cloud_redis.Instance]: return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore - @property - def get_instance_auth_string(self) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - cloud_redis.InstanceAuthString]: - return self._GetInstanceAuthString(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_instance(self) -> Callable[ - [cloud_redis.ImportInstanceRequest], - operations_pb2.Operation]: - return self._ImportInstance(self._session, self._host, self._interceptor) # type: ignore - @property def list_instances(self) -> Callable[ [cloud_redis.ListInstancesRequest], cloud_redis.ListInstancesResponse]: return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore - @property - def reschedule_maintenance(self) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - operations_pb2.Operation]: - return self._RescheduleMaintenance(self._session, self._host, self._interceptor) # type: ignore - @property def update_instance(self) -> Callable[ [cloud_redis.UpdateInstanceRequest], operations_pb2.Operation]: return self._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore - @property - def upgrade_instance(self) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - operations_pb2.Operation]: - return self._UpgradeInstance(self._session, self._host, self._interceptor) # type: ignore - @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_base.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_base.py index e63a3d8503..df8a6cd7c8 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_base.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_base.py @@ -169,98 +169,6 @@ def _get_query_params_json(transcoded_request): return query_params - class _BaseExportInstance: - 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': '/v1/{name=projects/*/locations/*/instances/*}:export', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = cloud_redis.ExportInstanceRequest.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=False - ) - 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=False, - )) - query_params.update(_BaseCloudRedisRestTransport._BaseExportInstance._get_unset_required_fields(query_params)) - - return query_params - - class _BaseFailoverInstance: - 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': '/v1/{name=projects/*/locations/*/instances/*}:failover', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = cloud_redis.FailoverInstanceRequest.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=False - ) - 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=False, - )) - query_params.update(_BaseCloudRedisRestTransport._BaseFailoverInstance._get_unset_required_fields(query_params)) - - return query_params - class _BaseGetInstance: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -297,88 +205,6 @@ def _get_query_params_json(transcoded_request): return query_params - class _BaseGetInstanceAuthString: - 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': '/v1/{name=projects/*/locations/*/instances/*}/authString', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = cloud_redis.GetInstanceAuthStringRequest.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=False, - )) - query_params.update(_BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_unset_required_fields(query_params)) - - return query_params - - class _BaseImportInstance: - 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': '/v1/{name=projects/*/locations/*/instances/*}:import', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = cloud_redis.ImportInstanceRequest.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=False - ) - 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=False, - )) - query_params.update(_BaseCloudRedisRestTransport._BaseImportInstance._get_unset_required_fields(query_params)) - - return query_params - class _BaseListInstances: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -415,52 +241,6 @@ def _get_query_params_json(transcoded_request): return query_params - class _BaseRescheduleMaintenance: - 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': '/v1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = cloud_redis.RescheduleMaintenanceRequest.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=False - ) - 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=False, - )) - query_params.update(_BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_unset_required_fields(query_params)) - - return query_params - class _BaseUpdateInstance: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -507,52 +287,6 @@ def _get_query_params_json(transcoded_request): return query_params - class _BaseUpgradeInstance: - 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': '/v1/{name=projects/*/locations/*/instances/*}:upgrade', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = cloud_redis.UpgradeInstanceRequest.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=False - ) - 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=False, - )) - query_params.update(_BaseCloudRedisRestTransport._BaseUpgradeInstance._get_unset_required_fields(query_params)) - - return query_params - class _BaseGetLocation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/types/__init__.py b/tests/integration/goldens/redis/google/cloud/redis_v1/types/__init__.py index 6afcaca198..a051e1e144 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/types/__init__.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/types/__init__.py @@ -16,59 +16,33 @@ from .cloud_redis import ( CreateInstanceRequest, DeleteInstanceRequest, - ExportInstanceRequest, - FailoverInstanceRequest, - GcsDestination, - GcsSource, - GetInstanceAuthStringRequest, GetInstanceRequest, - ImportInstanceRequest, - InputConfig, Instance, - InstanceAuthString, ListInstancesRequest, ListInstancesResponse, - LocationMetadata, MaintenancePolicy, MaintenanceSchedule, NodeInfo, OperationMetadata, - OutputConfig, PersistenceConfig, - RescheduleMaintenanceRequest, TlsCertificate, UpdateInstanceRequest, - UpgradeInstanceRequest, WeeklyMaintenanceWindow, - ZoneMetadata, ) __all__ = ( 'CreateInstanceRequest', 'DeleteInstanceRequest', - 'ExportInstanceRequest', - 'FailoverInstanceRequest', - 'GcsDestination', - 'GcsSource', - 'GetInstanceAuthStringRequest', 'GetInstanceRequest', - 'ImportInstanceRequest', - 'InputConfig', 'Instance', - 'InstanceAuthString', 'ListInstancesRequest', 'ListInstancesResponse', - 'LocationMetadata', 'MaintenancePolicy', 'MaintenanceSchedule', 'NodeInfo', 'OperationMetadata', - 'OutputConfig', 'PersistenceConfig', - 'RescheduleMaintenanceRequest', 'TlsCertificate', 'UpdateInstanceRequest', - 'UpgradeInstanceRequest', 'WeeklyMaintenanceWindow', - 'ZoneMetadata', ) diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/types/cloud_redis.py b/tests/integration/goldens/redis/google/cloud/redis_v1/types/cloud_redis.py index 50ca82ff02..a831851aa1 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/types/cloud_redis.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/types/cloud_redis.py @@ -32,29 +32,16 @@ 'NodeInfo', 'Instance', 'PersistenceConfig', - 'RescheduleMaintenanceRequest', 'MaintenancePolicy', 'WeeklyMaintenanceWindow', 'MaintenanceSchedule', 'ListInstancesRequest', 'ListInstancesResponse', 'GetInstanceRequest', - 'GetInstanceAuthStringRequest', - 'InstanceAuthString', 'CreateInstanceRequest', 'UpdateInstanceRequest', - 'UpgradeInstanceRequest', 'DeleteInstanceRequest', - 'GcsSource', - 'InputConfig', - 'ImportInstanceRequest', - 'GcsDestination', - 'OutputConfig', - 'ExportInstanceRequest', - 'FailoverInstanceRequest', 'OperationMetadata', - 'LocationMetadata', - 'ZoneMetadata', 'TlsCertificate', }, ) @@ -631,61 +618,6 @@ class SnapshotPeriod(proto.Enum): ) -class RescheduleMaintenanceRequest(proto.Message): - r"""Request for - [RescheduleMaintenance][google.cloud.redis.v1.CloudRedis.RescheduleMaintenance]. - - Attributes: - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - reschedule_type (google.cloud.redis_v1.types.RescheduleMaintenanceRequest.RescheduleType): - Required. If reschedule type is SPECIFIC_TIME, must set up - schedule_time as well. - schedule_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. Timestamp when the maintenance shall be - rescheduled to if reschedule_type=SPECIFIC_TIME, in RFC 3339 - format, for example ``2012-11-15T16:19:00.094Z``. - """ - class RescheduleType(proto.Enum): - r"""Reschedule options. - - Values: - RESCHEDULE_TYPE_UNSPECIFIED (0): - Not set. - IMMEDIATE (1): - If the user wants to schedule the maintenance - to happen now. - NEXT_AVAILABLE_WINDOW (2): - If the user wants to use the existing - maintenance policy to find the next available - window. - SPECIFIC_TIME (3): - If the user wants to reschedule the - maintenance to a specific time. - """ - RESCHEDULE_TYPE_UNSPECIFIED = 0 - IMMEDIATE = 1 - NEXT_AVAILABLE_WINDOW = 2 - SPECIFIC_TIME = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - reschedule_type: RescheduleType = proto.Field( - proto.ENUM, - number=2, - enum=RescheduleType, - ) - schedule_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - class MaintenancePolicy(proto.Message): r"""Maintenance policy for an instance. @@ -901,37 +833,6 @@ class GetInstanceRequest(proto.Message): ) -class GetInstanceAuthStringRequest(proto.Message): - r"""Request for - [GetInstanceAuthString][google.cloud.redis.v1.CloudRedis.GetInstanceAuthString]. - - Attributes: - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class InstanceAuthString(proto.Message): - r"""Instance AUTH string details. - - Attributes: - auth_string (str): - AUTH string set on the instance. - """ - - auth_string: str = proto.Field( - proto.STRING, - number=1, - ) - - class CreateInstanceRequest(proto.Message): r"""Request for [CreateInstance][google.cloud.redis.v1.CloudRedis.CreateInstance]. @@ -1003,30 +904,6 @@ class UpdateInstanceRequest(proto.Message): ) -class UpgradeInstanceRequest(proto.Message): - r"""Request for - [UpgradeInstance][google.cloud.redis.v1.CloudRedis.UpgradeInstance]. - - Attributes: - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - redis_version (str): - Required. Specifies the target version of - Redis software to upgrade to. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - redis_version: str = proto.Field( - proto.STRING, - number=2, - ) - - class DeleteInstanceRequest(proto.Message): r"""Request for [DeleteInstance][google.cloud.redis.v1.CloudRedis.DeleteInstance]. @@ -1044,174 +921,6 @@ class DeleteInstanceRequest(proto.Message): ) -class GcsSource(proto.Message): - r"""The Cloud Storage location for the input content - - Attributes: - uri (str): - Required. Source data URI. (e.g. - 'gs://my_bucket/my_object'). - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class InputConfig(proto.Message): - r"""The input content - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_source (google.cloud.redis_v1.types.GcsSource): - Google Cloud Storage location where input - content is located. - - This field is a member of `oneof`_ ``source``. - """ - - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='GcsSource', - ) - - -class ImportInstanceRequest(proto.Message): - r"""Request for - [Import][google.cloud.redis.v1.CloudRedis.ImportInstance]. - - Attributes: - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - input_config (google.cloud.redis_v1.types.InputConfig): - Required. Specify data to be imported. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - input_config: 'InputConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='InputConfig', - ) - - -class GcsDestination(proto.Message): - r"""The Cloud Storage location for the output content - - Attributes: - uri (str): - Required. Data destination URI (e.g. - 'gs://my_bucket/my_object'). Existing files will be - overwritten. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class OutputConfig(proto.Message): - r"""The output content - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_destination (google.cloud.redis_v1.types.GcsDestination): - Google Cloud Storage destination for output - content. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_destination: 'GcsDestination' = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='GcsDestination', - ) - - -class ExportInstanceRequest(proto.Message): - r"""Request for - [Export][google.cloud.redis.v1.CloudRedis.ExportInstance]. - - Attributes: - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - output_config (google.cloud.redis_v1.types.OutputConfig): - Required. Specify data to be exported. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - output_config: 'OutputConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='OutputConfig', - ) - - -class FailoverInstanceRequest(proto.Message): - r"""Request for - [Failover][google.cloud.redis.v1.CloudRedis.FailoverInstance]. - - Attributes: - name (str): - Required. Redis instance resource name using the form: - ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` - where ``location_id`` refers to a GCP region. - data_protection_mode (google.cloud.redis_v1.types.FailoverInstanceRequest.DataProtectionMode): - Optional. Available data protection modes that the user can - choose. If it's unspecified, data protection mode will be - LIMITED_DATA_LOSS by default. - """ - class DataProtectionMode(proto.Enum): - r"""Specifies different modes of operation in relation to the - data retention. - - Values: - DATA_PROTECTION_MODE_UNSPECIFIED (0): - Defaults to LIMITED_DATA_LOSS if a data protection mode is - not specified. - LIMITED_DATA_LOSS (1): - Instance failover will be protected with data - loss control. More specifically, the failover - will only be performed if the current - replication offset diff between primary and - replica is under a certain threshold. - FORCE_DATA_LOSS (2): - Instance failover will be performed without - data loss control. - """ - DATA_PROTECTION_MODE_UNSPECIFIED = 0 - LIMITED_DATA_LOSS = 1 - FORCE_DATA_LOSS = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - data_protection_mode: DataProtectionMode = proto.Field( - proto.ENUM, - number=2, - enum=DataProtectionMode, - ) - - class OperationMetadata(proto.Message): r"""Represents the v1 metadata of the long-running operation. @@ -1265,36 +974,6 @@ class OperationMetadata(proto.Message): ) -class LocationMetadata(proto.Message): - r"""This location metadata represents additional configuration options - for a given location where a Redis instance may be created. All - fields are output only. It is returned as content of the - ``google.cloud.location.Location.metadata`` field. - - Attributes: - available_zones (MutableMapping[str, google.cloud.redis_v1.types.ZoneMetadata]): - Output only. The set of available zones in the location. The - map is keyed by the lowercase ID of each zone, as defined by - GCE. These keys can be specified in ``location_id`` or - ``alternative_location_id`` fields when creating a Redis - instance. - """ - - available_zones: MutableMapping[str, 'ZoneMetadata'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message='ZoneMetadata', - ) - - -class ZoneMetadata(proto.Message): - r"""Defines specific information for a particular zone. Currently - empty and reserved for future use only. - - """ - - class TlsCertificate(proto.Message): r"""TlsCertificate Resource diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_export_instance_async.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_export_instance_async.py deleted file mode 100755 index bc2a58ff39..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_export_instance_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExportInstance -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_ExportInstance_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -async def sample_export_instance(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - output_config = redis_v1.OutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = redis_v1.ExportInstanceRequest( - name="name_value", - output_config=output_config, - ) - - # Make the request - operation = client.export_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_ExportInstance_async] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_export_instance_sync.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_export_instance_sync.py deleted file mode 100755 index a3e059a90f..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_export_instance_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExportInstance -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_ExportInstance_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -def sample_export_instance(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - output_config = redis_v1.OutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = redis_v1.ExportInstanceRequest( - name="name_value", - output_config=output_config, - ) - - # Make the request - operation = client.export_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_ExportInstance_sync] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_failover_instance_async.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_failover_instance_async.py deleted file mode 100755 index bc5eb5bf71..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_failover_instance_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for FailoverInstance -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_FailoverInstance_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -async def sample_failover_instance(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - request = redis_v1.FailoverInstanceRequest( - name="name_value", - ) - - # Make the request - operation = client.failover_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_FailoverInstance_async] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_failover_instance_sync.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_failover_instance_sync.py deleted file mode 100755 index 221da9018e..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_failover_instance_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for FailoverInstance -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_FailoverInstance_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -def sample_failover_instance(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - request = redis_v1.FailoverInstanceRequest( - name="name_value", - ) - - # Make the request - operation = client.failover_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_FailoverInstance_sync] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_get_instance_auth_string_async.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_get_instance_auth_string_async.py deleted file mode 100755 index e79a81d7b7..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_get_instance_auth_string_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetInstanceAuthString -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_GetInstanceAuthString_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -async def sample_get_instance_auth_string(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - request = redis_v1.GetInstanceAuthStringRequest( - name="name_value", - ) - - # Make the request - response = await client.get_instance_auth_string(request=request) - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_GetInstanceAuthString_async] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_get_instance_auth_string_sync.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_get_instance_auth_string_sync.py deleted file mode 100755 index 440b4db35b..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_get_instance_auth_string_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetInstanceAuthString -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_GetInstanceAuthString_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -def sample_get_instance_auth_string(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - request = redis_v1.GetInstanceAuthStringRequest( - name="name_value", - ) - - # Make the request - response = client.get_instance_auth_string(request=request) - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_GetInstanceAuthString_sync] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_import_instance_async.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_import_instance_async.py deleted file mode 100755 index 8384b9c187..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_import_instance_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportInstance -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_ImportInstance_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -async def sample_import_instance(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - input_config = redis_v1.InputConfig() - input_config.gcs_source.uri = "uri_value" - - request = redis_v1.ImportInstanceRequest( - name="name_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_ImportInstance_async] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_import_instance_sync.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_import_instance_sync.py deleted file mode 100755 index 43e5fb5a17..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_import_instance_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportInstance -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_ImportInstance_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -def sample_import_instance(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - input_config = redis_v1.InputConfig() - input_config.gcs_source.uri = "uri_value" - - request = redis_v1.ImportInstanceRequest( - name="name_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_ImportInstance_sync] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_reschedule_maintenance_async.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_reschedule_maintenance_async.py deleted file mode 100755 index 9ff86bb0c7..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_reschedule_maintenance_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RescheduleMaintenance -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_RescheduleMaintenance_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -async def sample_reschedule_maintenance(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - request = redis_v1.RescheduleMaintenanceRequest( - name="name_value", - reschedule_type="SPECIFIC_TIME", - ) - - # Make the request - operation = client.reschedule_maintenance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_RescheduleMaintenance_async] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_reschedule_maintenance_sync.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_reschedule_maintenance_sync.py deleted file mode 100755 index be55eed886..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_reschedule_maintenance_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RescheduleMaintenance -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_RescheduleMaintenance_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -def sample_reschedule_maintenance(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - request = redis_v1.RescheduleMaintenanceRequest( - name="name_value", - reschedule_type="SPECIFIC_TIME", - ) - - # Make the request - operation = client.reschedule_maintenance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_RescheduleMaintenance_sync] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_upgrade_instance_async.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_upgrade_instance_async.py deleted file mode 100755 index d728569385..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_upgrade_instance_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpgradeInstance -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_UpgradeInstance_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -async def sample_upgrade_instance(): - # Create a client - client = redis_v1.CloudRedisAsyncClient() - - # Initialize request argument(s) - request = redis_v1.UpgradeInstanceRequest( - name="name_value", - redis_version="redis_version_value", - ) - - # Make the request - operation = client.upgrade_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_UpgradeInstance_async] diff --git a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_upgrade_instance_sync.py b/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_upgrade_instance_sync.py deleted file mode 100755 index 2682878bbb..0000000000 --- a/tests/integration/goldens/redis/samples/generated_samples/redis_v1_generated_cloud_redis_upgrade_instance_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpgradeInstance -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-redis - - -# [START redis_v1_generated_CloudRedis_UpgradeInstance_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import redis_v1 - - -def sample_upgrade_instance(): - # Create a client - client = redis_v1.CloudRedisClient() - - # Initialize request argument(s) - request = redis_v1.UpgradeInstanceRequest( - name="name_value", - redis_version="redis_version_value", - ) - - # Make the request - operation = client.upgrade_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END redis_v1_generated_CloudRedis_UpgradeInstance_sync] diff --git a/tests/integration/goldens/redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1.json b/tests/integration/goldens/redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1.json index 78f872bc4a..467e4c62ce 100755 --- a/tests/integration/goldens/redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1.json +++ b/tests/integration/goldens/redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1.json @@ -357,851 +357,22 @@ "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient", "shortName": "CloudRedisAsyncClient" }, - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient.export_instance", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.ExportInstance", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "ExportInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.ExportInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "output_config", - "type": "google.cloud.redis_v1.types.OutputConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_instance" - }, - "description": "Sample for ExportInstance", - "file": "redis_v1_generated_cloud_redis_export_instance_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_ExportInstance_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_export_instance_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisClient", - "shortName": "CloudRedisClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisClient.export_instance", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.ExportInstance", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "ExportInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.ExportInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "output_config", - "type": "google.cloud.redis_v1.types.OutputConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_instance" - }, - "description": "Sample for ExportInstance", - "file": "redis_v1_generated_cloud_redis_export_instance_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_ExportInstance_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_export_instance_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient", - "shortName": "CloudRedisAsyncClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient.failover_instance", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.FailoverInstance", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "FailoverInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.FailoverInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data_protection_mode", - "type": "google.cloud.redis_v1.types.FailoverInstanceRequest.DataProtectionMode" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "failover_instance" - }, - "description": "Sample for FailoverInstance", - "file": "redis_v1_generated_cloud_redis_failover_instance_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_FailoverInstance_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_failover_instance_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisClient", - "shortName": "CloudRedisClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisClient.failover_instance", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.FailoverInstance", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "FailoverInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.FailoverInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data_protection_mode", - "type": "google.cloud.redis_v1.types.FailoverInstanceRequest.DataProtectionMode" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "failover_instance" - }, - "description": "Sample for FailoverInstance", - "file": "redis_v1_generated_cloud_redis_failover_instance_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_FailoverInstance_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_failover_instance_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient", - "shortName": "CloudRedisAsyncClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient.get_instance_auth_string", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.GetInstanceAuthString", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "GetInstanceAuthString" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.GetInstanceAuthStringRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.redis_v1.types.InstanceAuthString", - "shortName": "get_instance_auth_string" - }, - "description": "Sample for GetInstanceAuthString", - "file": "redis_v1_generated_cloud_redis_get_instance_auth_string_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_GetInstanceAuthString_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_get_instance_auth_string_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisClient", - "shortName": "CloudRedisClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisClient.get_instance_auth_string", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.GetInstanceAuthString", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "GetInstanceAuthString" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.GetInstanceAuthStringRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.redis_v1.types.InstanceAuthString", - "shortName": "get_instance_auth_string" - }, - "description": "Sample for GetInstanceAuthString", - "file": "redis_v1_generated_cloud_redis_get_instance_auth_string_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_GetInstanceAuthString_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_get_instance_auth_string_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient", - "shortName": "CloudRedisAsyncClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient.get_instance", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.GetInstance", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "GetInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.GetInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.redis_v1.types.Instance", - "shortName": "get_instance" - }, - "description": "Sample for GetInstance", - "file": "redis_v1_generated_cloud_redis_get_instance_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_GetInstance_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_get_instance_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisClient", - "shortName": "CloudRedisClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisClient.get_instance", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.GetInstance", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "GetInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.GetInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.redis_v1.types.Instance", - "shortName": "get_instance" - }, - "description": "Sample for GetInstance", - "file": "redis_v1_generated_cloud_redis_get_instance_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_GetInstance_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_get_instance_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient", - "shortName": "CloudRedisAsyncClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient.import_instance", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.ImportInstance", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "ImportInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.ImportInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "input_config", - "type": "google.cloud.redis_v1.types.InputConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_instance" - }, - "description": "Sample for ImportInstance", - "file": "redis_v1_generated_cloud_redis_import_instance_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_ImportInstance_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_import_instance_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisClient", - "shortName": "CloudRedisClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisClient.import_instance", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.ImportInstance", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "ImportInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.ImportInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "input_config", - "type": "google.cloud.redis_v1.types.InputConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_instance" - }, - "description": "Sample for ImportInstance", - "file": "redis_v1_generated_cloud_redis_import_instance_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_ImportInstance_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_import_instance_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient", - "shortName": "CloudRedisAsyncClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient.list_instances", + "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient.get_instance", "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.ListInstances", + "fullName": "google.cloud.redis.v1.CloudRedis.GetInstance", "service": { "fullName": "google.cloud.redis.v1.CloudRedis", "shortName": "CloudRedis" }, - "shortName": "ListInstances" + "shortName": "GetInstance" }, "parameters": [ { "name": "request", - "type": "google.cloud.redis_v1.types.ListInstancesRequest" + "type": "google.cloud.redis_v1.types.GetInstanceRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -1217,22 +388,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.redis_v1.services.cloud_redis.pagers.ListInstancesAsyncPager", - "shortName": "list_instances" + "resultType": "google.cloud.redis_v1.types.Instance", + "shortName": "get_instance" }, - "description": "Sample for ListInstances", - "file": "redis_v1_generated_cloud_redis_list_instances_async.py", + "description": "Sample for GetInstance", + "file": "redis_v1_generated_cloud_redis_get_instance_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_ListInstances_async", + "regionTag": "redis_v1_generated_CloudRedis_GetInstance_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1252,12 +423,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "redis_v1_generated_cloud_redis_list_instances_async.py" + "title": "redis_v1_generated_cloud_redis_get_instance_async.py" }, { "canonical": true, @@ -1266,22 +437,22 @@ "fullName": "google.cloud.redis_v1.CloudRedisClient", "shortName": "CloudRedisClient" }, - "fullName": "google.cloud.redis_v1.CloudRedisClient.list_instances", + "fullName": "google.cloud.redis_v1.CloudRedisClient.get_instance", "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.ListInstances", + "fullName": "google.cloud.redis.v1.CloudRedis.GetInstance", "service": { "fullName": "google.cloud.redis.v1.CloudRedis", "shortName": "CloudRedis" }, - "shortName": "ListInstances" + "shortName": "GetInstance" }, "parameters": [ { "name": "request", - "type": "google.cloud.redis_v1.types.ListInstancesRequest" + "type": "google.cloud.redis_v1.types.GetInstanceRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -1297,22 +468,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.redis_v1.services.cloud_redis.pagers.ListInstancesPager", - "shortName": "list_instances" + "resultType": "google.cloud.redis_v1.types.Instance", + "shortName": "get_instance" }, - "description": "Sample for ListInstances", - "file": "redis_v1_generated_cloud_redis_list_instances_sync.py", + "description": "Sample for GetInstance", + "file": "redis_v1_generated_cloud_redis_get_instance_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_ListInstances_sync", + "regionTag": "redis_v1_generated_CloudRedis_GetInstance_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1332,12 +503,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "redis_v1_generated_cloud_redis_list_instances_sync.py" + "title": "redis_v1_generated_cloud_redis_get_instance_sync.py" }, { "canonical": true, @@ -1347,32 +518,24 @@ "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient", "shortName": "CloudRedisAsyncClient" }, - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient.reschedule_maintenance", + "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient.list_instances", "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.RescheduleMaintenance", + "fullName": "google.cloud.redis.v1.CloudRedis.ListInstances", "service": { "fullName": "google.cloud.redis.v1.CloudRedis", "shortName": "CloudRedis" }, - "shortName": "RescheduleMaintenance" + "shortName": "ListInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.redis_v1.types.RescheduleMaintenanceRequest" + "type": "google.cloud.redis_v1.types.ListInstancesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, - { - "name": "reschedule_type", - "type": "google.cloud.redis_v1.types.RescheduleMaintenanceRequest.RescheduleType" - }, - { - "name": "schedule_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1386,22 +549,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "reschedule_maintenance" + "resultType": "google.cloud.redis_v1.services.cloud_redis.pagers.ListInstancesAsyncPager", + "shortName": "list_instances" }, - "description": "Sample for RescheduleMaintenance", - "file": "redis_v1_generated_cloud_redis_reschedule_maintenance_async.py", + "description": "Sample for ListInstances", + "file": "redis_v1_generated_cloud_redis_list_instances_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_RescheduleMaintenance_async", + "regionTag": "redis_v1_generated_CloudRedis_ListInstances_async", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1411,22 +574,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "redis_v1_generated_cloud_redis_reschedule_maintenance_async.py" + "title": "redis_v1_generated_cloud_redis_list_instances_async.py" }, { "canonical": true, @@ -1435,32 +598,24 @@ "fullName": "google.cloud.redis_v1.CloudRedisClient", "shortName": "CloudRedisClient" }, - "fullName": "google.cloud.redis_v1.CloudRedisClient.reschedule_maintenance", + "fullName": "google.cloud.redis_v1.CloudRedisClient.list_instances", "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.RescheduleMaintenance", + "fullName": "google.cloud.redis.v1.CloudRedis.ListInstances", "service": { "fullName": "google.cloud.redis.v1.CloudRedis", "shortName": "CloudRedis" }, - "shortName": "RescheduleMaintenance" + "shortName": "ListInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.redis_v1.types.RescheduleMaintenanceRequest" + "type": "google.cloud.redis_v1.types.ListInstancesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, - { - "name": "reschedule_type", - "type": "google.cloud.redis_v1.types.RescheduleMaintenanceRequest.RescheduleType" - }, - { - "name": "schedule_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1474,22 +629,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "reschedule_maintenance" + "resultType": "google.cloud.redis_v1.services.cloud_redis.pagers.ListInstancesPager", + "shortName": "list_instances" }, - "description": "Sample for RescheduleMaintenance", - "file": "redis_v1_generated_cloud_redis_reschedule_maintenance_sync.py", + "description": "Sample for ListInstances", + "file": "redis_v1_generated_cloud_redis_list_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_RescheduleMaintenance_sync", + "regionTag": "redis_v1_generated_CloudRedis_ListInstances_sync", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1499,22 +654,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "redis_v1_generated_cloud_redis_reschedule_maintenance_sync.py" + "title": "redis_v1_generated_cloud_redis_list_instances_sync.py" }, { "canonical": true, @@ -1684,175 +839,6 @@ } ], "title": "redis_v1_generated_cloud_redis_update_instance_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient", - "shortName": "CloudRedisAsyncClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisAsyncClient.upgrade_instance", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.UpgradeInstance", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "UpgradeInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.UpgradeInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "redis_version", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "upgrade_instance" - }, - "description": "Sample for UpgradeInstance", - "file": "redis_v1_generated_cloud_redis_upgrade_instance_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_UpgradeInstance_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_upgrade_instance_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.redis_v1.CloudRedisClient", - "shortName": "CloudRedisClient" - }, - "fullName": "google.cloud.redis_v1.CloudRedisClient.upgrade_instance", - "method": { - "fullName": "google.cloud.redis.v1.CloudRedis.UpgradeInstance", - "service": { - "fullName": "google.cloud.redis.v1.CloudRedis", - "shortName": "CloudRedis" - }, - "shortName": "UpgradeInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.redis_v1.types.UpgradeInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "redis_version", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "upgrade_instance" - }, - "description": "Sample for UpgradeInstance", - "file": "redis_v1_generated_cloud_redis_upgrade_instance_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "redis_v1_generated_CloudRedis_UpgradeInstance_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "redis_v1_generated_cloud_redis_upgrade_instance_sync.py" } ] } diff --git a/tests/integration/goldens/redis/scripts/fixup_redis_v1_keywords.py b/tests/integration/goldens/redis/scripts/fixup_redis_v1_keywords.py index 5ea0edd079..7022cedcf3 100755 --- a/tests/integration/goldens/redis/scripts/fixup_redis_v1_keywords.py +++ b/tests/integration/goldens/redis/scripts/fixup_redis_v1_keywords.py @@ -41,15 +41,9 @@ class redisCallTransformer(cst.CSTTransformer): METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'create_instance': ('parent', 'instance_id', 'instance', ), 'delete_instance': ('name', ), - 'export_instance': ('name', 'output_config', ), - 'failover_instance': ('name', 'data_protection_mode', ), 'get_instance': ('name', ), - 'get_instance_auth_string': ('name', ), - 'import_instance': ('name', 'input_config', ), 'list_instances': ('parent', 'page_size', 'page_token', ), - 'reschedule_maintenance': ('name', 'reschedule_type', 'schedule_time', ), 'update_instance': ('update_mask', 'instance', ), - 'upgrade_instance': ('name', 'redis_version', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py b/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py index d46839b7a8..cf39e33d4e 100755 --- a/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -1659,315 +1659,6 @@ async def test_get_instance_flattened_error_async(): ) -@pytest.mark.parametrize("request_type", [ - cloud_redis.GetInstanceAuthStringRequest, - dict, -]) -def test_get_instance_auth_string(request_type, transport: str = 'grpc'): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_instance_auth_string), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloud_redis.InstanceAuthString( - auth_string='auth_string_value', - ) - response = client.get_instance_auth_string(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = cloud_redis.GetInstanceAuthStringRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis.InstanceAuthString) - assert response.auth_string == 'auth_string_value' - - -def test_get_instance_auth_string_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 = CloudRedisClient( - 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 = cloud_redis.GetInstanceAuthStringRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_instance_auth_string(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.GetInstanceAuthStringRequest( - name='name_value', - ) - -def test_get_instance_auth_string_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 = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_instance_auth_string 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_auth_string] = mock_rpc - request = {} - client.get_instance_auth_string(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_instance_auth_string(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_instance_auth_string_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 = CloudRedisAsyncClient( - 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.get_instance_auth_string in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_instance_auth_string] = mock_rpc - - request = {} - await client.get_instance_auth_string(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_instance_auth_string(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_instance_auth_string_async(transport: str = 'grpc_asyncio', request_type=cloud_redis.GetInstanceAuthStringRequest): - client = CloudRedisAsyncClient( - 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.get_instance_auth_string), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(cloud_redis.InstanceAuthString( - auth_string='auth_string_value', - )) - response = await client.get_instance_auth_string(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = cloud_redis.GetInstanceAuthStringRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis.InstanceAuthString) - assert response.auth_string == 'auth_string_value' - - -@pytest.mark.asyncio -async def test_get_instance_auth_string_async_from_dict(): - await test_get_instance_auth_string_async(request_type=dict) - -def test_get_instance_auth_string_field_headers(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.GetInstanceAuthStringRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), - '__call__') as call: - call.return_value = cloud_redis.InstanceAuthString() - client.get_instance_auth_string(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_instance_auth_string_field_headers_async(): - client = CloudRedisAsyncClient( - 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 = cloud_redis.GetInstanceAuthStringRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloud_redis.InstanceAuthString()) - await client.get_instance_auth_string(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_instance_auth_string_flattened(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloud_redis.InstanceAuthString() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_instance_auth_string( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_instance_auth_string_flattened_error(): - client = CloudRedisClient( - 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_instance_auth_string( - cloud_redis.GetInstanceAuthStringRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_instance_auth_string_flattened_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = cloud_redis.InstanceAuthString() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloud_redis.InstanceAuthString()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_instance_auth_string( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_instance_auth_string_flattened_error_async(): - client = CloudRedisAsyncClient( - 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_instance_auth_string( - cloud_redis.GetInstanceAuthStringRequest(), - name='name_value', - ) - - @pytest.mark.parametrize("request_type", [ cloud_redis.CreateInstanceRequest, dict, @@ -2633,10 +2324,10 @@ async def test_update_instance_flattened_error_async(): @pytest.mark.parametrize("request_type", [ - cloud_redis.UpgradeInstanceRequest, + cloud_redis.DeleteInstanceRequest, dict, ]) -def test_upgrade_instance(request_type, transport: str = 'grpc'): +def test_delete_instance(request_type, transport: str = 'grpc'): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2648,23 +2339,23 @@ def test_upgrade_instance(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.upgrade_instance), + type(client.transport.delete_instance), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.upgrade_instance(request) + response = client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = cloud_redis.UpgradeInstanceRequest() + request = cloud_redis.DeleteInstanceRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_upgrade_instance_non_empty_request_with_auto_populated_field(): +def test_delete_instance_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 = CloudRedisClient( @@ -2675,25 +2366,23 @@ def test_upgrade_instance_non_empty_request_with_auto_populated_field(): # 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 = cloud_redis.UpgradeInstanceRequest( + request = cloud_redis.DeleteInstanceRequest( name='name_value', - redis_version='redis_version_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.upgrade_instance), + type(client.transport.delete_instance), '__call__') as call: call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.upgrade_instance(request=request) + client.delete_instance(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.UpgradeInstanceRequest( + assert args[0] == cloud_redis.DeleteInstanceRequest( name='name_value', - redis_version='redis_version_value', ) -def test_upgrade_instance_use_cached_wrapped_rpc(): +def test_delete_instance_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: @@ -2707,14 +2396,14 @@ def test_upgrade_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.upgrade_instance 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.upgrade_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc request = {} - client.upgrade_instance(request) + client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -2724,14 +2413,14 @@ def test_upgrade_instance_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.upgrade_instance(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 @pytest.mark.asyncio -async def test_upgrade_instance_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_instance_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: @@ -2745,15 +2434,15 @@ async def test_upgrade_instance_async_use_cached_wrapped_rpc(transport: str = "g wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.upgrade_instance in client._client._transport._wrapped_methods + assert client._client._transport.delete_instance 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.upgrade_instance] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.delete_instance] = mock_rpc request = {} - await client.upgrade_instance(request) + await client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -2763,14 +2452,14 @@ async def test_upgrade_instance_async_use_cached_wrapped_rpc(transport: str = "g # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.upgrade_instance(request) + await 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_upgrade_instance_async(transport: str = 'grpc_asyncio', request_type=cloud_redis.UpgradeInstanceRequest): +async def test_delete_instance_async(transport: str = 'grpc_asyncio', request_type=cloud_redis.DeleteInstanceRequest): client = CloudRedisAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2782,18 +2471,18 @@ async def test_upgrade_instance_async(transport: str = 'grpc_asyncio', request_t # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.upgrade_instance), + type(client.transport.delete_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') ) - response = await client.upgrade_instance(request) + response = await client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = cloud_redis.UpgradeInstanceRequest() + request = cloud_redis.DeleteInstanceRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -2801,26 +2490,26 @@ async def test_upgrade_instance_async(transport: str = 'grpc_asyncio', request_t @pytest.mark.asyncio -async def test_upgrade_instance_async_from_dict(): - await test_upgrade_instance_async(request_type=dict) +async def test_delete_instance_async_from_dict(): + await test_delete_instance_async(request_type=dict) -def test_upgrade_instance_field_headers(): +def test_delete_instance_field_headers(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = cloud_redis.UpgradeInstanceRequest() + request = cloud_redis.DeleteInstanceRequest() request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.upgrade_instance), + type(client.transport.delete_instance), '__call__') as call: call.return_value = operations_pb2.Operation(name='operations/op') - client.upgrade_instance(request) + client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2836,23 +2525,23 @@ def test_upgrade_instance_field_headers(): @pytest.mark.asyncio -async def test_upgrade_instance_field_headers_async(): +async def test_delete_instance_field_headers_async(): client = CloudRedisAsyncClient( 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 = cloud_redis.UpgradeInstanceRequest() + request = cloud_redis.DeleteInstanceRequest() request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.upgrade_instance), + type(client.transport.delete_instance), '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.upgrade_instance(request) + await client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2867,22 +2556,21 @@ async def test_upgrade_instance_field_headers_async(): ) in kw['metadata'] -def test_upgrade_instance_flattened(): +def test_delete_instance_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.upgrade_instance), + type(client.transport.delete_instance), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.upgrade_instance( + client.delete_instance( name='name_value', - redis_version='redis_version_value', ) # Establish that the underlying call was made with the expected @@ -2892,12 +2580,9 @@ def test_upgrade_instance_flattened(): arg = args[0].name mock_val = 'name_value' assert arg == mock_val - arg = args[0].redis_version - mock_val = 'redis_version_value' - assert arg == mock_val -def test_upgrade_instance_flattened_error(): +def test_delete_instance_flattened_error(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2905,21 +2590,20 @@ def test_upgrade_instance_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.upgrade_instance( - cloud_redis.UpgradeInstanceRequest(), + client.delete_instance( + cloud_redis.DeleteInstanceRequest(), name='name_value', - redis_version='redis_version_value', ) @pytest.mark.asyncio -async def test_upgrade_instance_flattened_async(): +async def test_delete_instance_flattened_async(): client = CloudRedisAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.upgrade_instance), + type(client.transport.delete_instance), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name='operations/op') @@ -2929,9 +2613,8 @@ async def test_upgrade_instance_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.upgrade_instance( + response = await client.delete_instance( name='name_value', - redis_version='redis_version_value', ) # Establish that the underlying call was made with the expected @@ -2941,12 +2624,9 @@ async def test_upgrade_instance_flattened_async(): arg = args[0].name mock_val = 'name_value' assert arg == mock_val - arg = args[0].redis_version - mock_val = 'redis_version_value' - assert arg == mock_val @pytest.mark.asyncio -async def test_upgrade_instance_flattened_error_async(): +async def test_delete_instance_flattened_error_async(): client = CloudRedisAsyncClient( credentials=async_anonymous_credentials(), ) @@ -2954,79 +2634,19 @@ async def test_upgrade_instance_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.upgrade_instance( - cloud_redis.UpgradeInstanceRequest(), + await client.delete_instance( + cloud_redis.DeleteInstanceRequest(), name='name_value', - redis_version='redis_version_value', ) -@pytest.mark.parametrize("request_type", [ - cloud_redis.ImportInstanceRequest, - dict, -]) -def test_import_instance(request_type, transport: str = 'grpc'): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = cloud_redis.ImportInstanceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_instance_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 = CloudRedisClient( - 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 = cloud_redis.ImportInstanceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_instance), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.import_instance(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ImportInstanceRequest( - name='name_value', - ) - -def test_import_instance_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: client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) # Should wrap all calls on client creation @@ -3034,326 +2654,229 @@ def test_import_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.import_instance 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.import_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + request = {} - client.import_instance(request) + client.list_instances(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.import_instance(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 -@pytest.mark.asyncio -async def test_import_instance_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 = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +def test_list_instances_rest_required_fields(request_type=cloud_redis.ListInstancesRequest): + transport_class = transports.CloudRedisRestTransport - # Ensure method has been cached - assert client._client._transport.import_instance in client._client._transport._wrapped_methods + 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 + )) - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.import_instance] = mock_rpc + # verify fields with default values are dropped - request = {} - await client.import_instance(request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_instances._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 default values are now present - # 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() + jsonified_request["parent"] = 'parent_value' - await client.import_instance(request) + 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_size", "page_token", )) + jsonified_request.update(unset_fields) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' -@pytest.mark.asyncio -async def test_import_instance_async(transport: str = 'grpc_asyncio', request_type=cloud_redis.ImportInstanceRequest): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', ) + request = request_type(**request_init) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_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') - ) - response = await client.import_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = cloud_redis.ImportInstanceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + # Designate an appropriate value for the returned response. + return_value = cloud_redis.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 + response_value = Response() + response_value.status_code = 200 -@pytest.mark.asyncio -async def test_import_instance_async_from_dict(): - await test_import_instance_async(request_type=dict) + # Convert return value to protobuf type + return_value = cloud_redis.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -def test_import_instance_field_headers(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + 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"} - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.ImportInstanceRequest() + response = client.list_instances(request) - request.name = 'name_value' + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_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 +def test_list_instances_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + unset_fields = transport.list_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) -@pytest.mark.asyncio -async def test_import_instance_field_headers_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), +def test_list_instances_rest_flattened(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.ImportInstanceRequest() + # 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 = cloud_redis.ListInstancesResponse() - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_instance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_instance(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'] + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) -def test_import_instance_flattened(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_redis.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"} - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.import_instance( - name='name_value', - input_config=cloud_redis.InputConfig(gcs_source=cloud_redis.GcsSource(uri='uri_value')), - ) + client.list_instances(**mock_args) # 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 - arg = args[0].input_config - mock_val = cloud_redis.InputConfig(gcs_source=cloud_redis.GcsSource(uri='uri_value')) - assert arg == mock_val + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, args[1]) -def test_import_instance_flattened_error(): +def test_list_instances_rest_flattened_error(transport: str = 'rest'): client = CloudRedisClient( 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.import_instance( - cloud_redis.ImportInstanceRequest(), - name='name_value', - input_config=cloud_redis.InputConfig(gcs_source=cloud_redis.GcsSource(uri='uri_value')), - ) - -@pytest.mark.asyncio -async def test_import_instance_flattened_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_instance), - '__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.import_instance( - name='name_value', - input_config=cloud_redis.InputConfig(gcs_source=cloud_redis.GcsSource(uri='uri_value')), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].input_config - mock_val = cloud_redis.InputConfig(gcs_source=cloud_redis.GcsSource(uri='uri_value')) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_import_instance_flattened_error_async(): - client = CloudRedisAsyncClient( - 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.import_instance( - cloud_redis.ImportInstanceRequest(), - name='name_value', - input_config=cloud_redis.InputConfig(gcs_source=cloud_redis.GcsSource(uri='uri_value')), + client.list_instances( + cloud_redis.ListInstancesRequest(), + parent='parent_value', ) -@pytest.mark.parametrize("request_type", [ - cloud_redis.ExportInstanceRequest, - dict, -]) -def test_export_instance(request_type, transport: str = 'grpc'): +def test_list_instances_rest_pager(transport: str = 'rest'): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.export_instance(request) + # 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 = ( + cloud_redis.ListInstancesResponse( + instances=[ + cloud_redis.Instance(), + cloud_redis.Instance(), + cloud_redis.Instance(), + ], + next_page_token='abc', + ), + cloud_redis.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + cloud_redis.ListInstancesResponse( + instances=[ + cloud_redis.Instance(), + ], + next_page_token='ghi', + ), + cloud_redis.ListInstancesResponse( + instances=[ + cloud_redis.Instance(), + cloud_redis.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = cloud_redis.ExportInstanceRequest() - assert args[0] == request + # Wrap the values into proper Response objs + response = tuple(cloud_redis.ListInstancesResponse.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 - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + sample_request = {'parent': 'projects/sample1/locations/sample2'} + pager = client.list_instances(request=sample_request) -def test_export_instance_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 = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_redis.Instance) + for i in results) - # 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 = cloud_redis.ExportInstanceRequest( - name='name_value', - ) + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_instance), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.export_instance(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ExportInstanceRequest( - name='name_value', - ) -def test_export_instance_use_cached_wrapped_rpc(): +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: client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) # Should wrap all calls on client creation @@ -3361,326 +2884,165 @@ def test_export_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.export_instance 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.export_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + request = {} - client.export_instance(request) + client.get_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.export_instance(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 -@pytest.mark.asyncio -async def test_export_instance_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 = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +def test_get_instance_rest_required_fields(request_type=cloud_redis.GetInstanceRequest): + transport_class = transports.CloudRedisRestTransport - # Ensure method has been cached - assert client._client._transport.export_instance in client._client._transport._wrapped_methods + 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 + )) - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.export_instance] = mock_rpc + # verify fields with default values are dropped - request = {} - await client.export_instance(request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_instance._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 default values are now present - # 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() + jsonified_request["name"] = 'name_value' - await client.export_instance(request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' -@pytest.mark.asyncio -async def test_export_instance_async(transport: str = 'grpc_asyncio', request_type=cloud_redis.ExportInstanceRequest): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', ) + request = request_type(**request_init) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_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') - ) - response = await client.export_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = cloud_redis.ExportInstanceRequest() - 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_export_instance_async_from_dict(): - await test_export_instance_async(request_type=dict) - -def test_export_instance_field_headers(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.ExportInstanceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_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 + # Designate an appropriate value for the returned response. + return_value = cloud_redis.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 - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_redis.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -@pytest.mark.asyncio -async def test_export_instance_field_headers_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - ) + 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"} - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.ExportInstanceRequest() + response = client.get_instance(request) - request.name = 'name_value' + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_instance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.export_instance(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_get_instance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) -def test_export_instance_flattened(): +def test_get_instance_rest_flattened(): client = CloudRedisClient( 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.export_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.export_instance( - name='name_value', - output_config=cloud_redis.OutputConfig(gcs_destination=cloud_redis.GcsDestination(uri='uri_value')), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].output_config - mock_val = cloud_redis.OutputConfig(gcs_destination=cloud_redis.GcsDestination(uri='uri_value')) - assert arg == mock_val - + # 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 = cloud_redis.Instance() -def test_export_instance_flattened_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.export_instance( - cloud_redis.ExportInstanceRequest(), + # get truthy value for each flattened field + mock_args = dict( name='name_value', - output_config=cloud_redis.OutputConfig(gcs_destination=cloud_redis.GcsDestination(uri='uri_value')), ) + mock_args.update(sample_request) -@pytest.mark.asyncio -async def test_export_instance_flattened_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_redis.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"} - 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.export_instance( - name='name_value', - output_config=cloud_redis.OutputConfig(gcs_destination=cloud_redis.GcsDestination(uri='uri_value')), - ) + client.get_instance(**mock_args) # 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 - arg = args[0].output_config - mock_val = cloud_redis.OutputConfig(gcs_destination=cloud_redis.GcsDestination(uri='uri_value')) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_export_instance_flattened_error_async(): - client = CloudRedisAsyncClient( - 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.export_instance( - cloud_redis.ExportInstanceRequest(), - name='name_value', - output_config=cloud_redis.OutputConfig(gcs_destination=cloud_redis.GcsDestination(uri='uri_value')), - ) + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, args[1]) -@pytest.mark.parametrize("request_type", [ - cloud_redis.FailoverInstanceRequest, - dict, -]) -def test_failover_instance(request_type, transport: str = 'grpc'): +def test_get_instance_rest_flattened_error(transport: str = 'rest'): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.failover_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = cloud_redis.FailoverInstanceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_failover_instance_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 = CloudRedisClient( - 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 = cloud_redis.FailoverInstanceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.failover_instance(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.FailoverInstanceRequest( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_instance( + cloud_redis.GetInstanceRequest(), name='name_value', ) -def test_failover_instance_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: client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) # Should wrap all calls on client creation @@ -3688,326 +3050,347 @@ def test_failover_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.failover_instance 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.failover_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + request = {} - client.failover_instance(request) + client.create_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.failover_instance(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 -@pytest.mark.asyncio -async def test_failover_instance_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 = CloudRedisAsyncClient( - 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.failover_instance in client._client._transport._wrapped_methods +def test_create_instance_rest_required_fields(request_type=cloud_redis.CreateInstanceRequest): + transport_class = transports.CloudRedisRestTransport - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.failover_instance] = mock_rpc - - request = {} - await client.failover_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.failover_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_failover_instance_async(transport: str = 'grpc_asyncio', request_type=cloud_redis.FailoverInstanceRequest): - client = CloudRedisAsyncClient( - 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 + )) - # Everything is optional in proto3 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 fields with default values are dropped + assert "instanceId" not in jsonified_request - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_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') - ) - response = await client.failover_instance(request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = cloud_redis.FailoverInstanceRequest() - assert args[0] == request + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + jsonified_request["parent"] = 'parent_value' + jsonified_request["instanceId"] = 'instance_id_value' + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("instance_id", )) + jsonified_request.update(unset_fields) -@pytest.mark.asyncio -async def test_failover_instance_async_from_dict(): - await test_failover_instance_async(request_type=dict) + # 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' -def test_failover_instance_field_headers(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), + transport='rest', ) + request = request_type(**request_init) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.FailoverInstanceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.failover_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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + # 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_failover_instance_field_headers_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - ) + 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"} - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.FailoverInstanceRequest() + response = client.create_instance(request) - request.name = 'name_value' + expected_params = [ + ( + "instanceId", + "", + ), + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.failover_instance(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_unset_required_fields(): + transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("instanceId", )) & set(("parent", "instanceId", "instance", ))) -def test_failover_instance_flattened(): +def test_create_instance_rest_flattened(): client = CloudRedisClient( 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.failover_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.failover_instance( - name='name_value', - data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, + # 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/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + instance_id='instance_id_value', + instance=cloud_redis.Instance(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_instance(**mock_args) # 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 - arg = args[0].data_protection_mode - mock_val = cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS - assert arg == mock_val + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, args[1]) -def test_failover_instance_flattened_error(): +def test_create_instance_rest_flattened_error(transport: str = 'rest'): client = CloudRedisClient( 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.failover_instance( - cloud_redis.FailoverInstanceRequest(), - name='name_value', - data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, + client.create_instance( + cloud_redis.CreateInstanceRequest(), + parent='parent_value', + instance_id='instance_id_value', + instance=cloud_redis.Instance(name='name_value'), ) -@pytest.mark.asyncio -async def test_failover_instance_flattened_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), - '__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.failover_instance( - name='name_value', - data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, +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 = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # 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 - arg = args[0].data_protection_mode - mock_val = cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS - assert arg == mock_val + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.asyncio -async def test_failover_instance_flattened_error_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - ) + # Ensure method has been cached + assert client._transport.update_instance in client._transport._wrapped_methods - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.failover_instance( - cloud_redis.FailoverInstanceRequest(), - name='name_value', - data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, - ) + # 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_instance] = mock_rpc + request = {} + client.update_instance(request) -@pytest.mark.parametrize("request_type", [ - cloud_redis.DeleteInstanceRequest, - dict, -]) -def test_delete_instance(request_type, transport: str = 'grpc'): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # 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_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_instance_rest_required_fields(request_type=cloud_redis.UpdateInstanceRequest): + transport_class = transports.CloudRedisRestTransport + + 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_instance._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_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 + + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', ) + request = request_type(**request_init) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() + # 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 - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_instance(request) + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = cloud_redis.DeleteInstanceRequest() - assert args[0] == request + 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 response is the type that we expect. - assert isinstance(response, future.Future) + response = client.update_instance(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params -def test_delete_instance_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. +def test_update_instance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", "instance", ))) + + +def test_update_instance_rest_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + 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 = cloud_redis.DeleteInstanceRequest( - name='name_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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'instance': {'name': 'projects/sample1/locations/sample2/instances/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + instance=cloud_redis.Instance(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.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/v1/{instance.name=projects/*/locations/*/instances/*}" % client.transport._host, args[1]) + + +def test_update_instance_rest_flattened_error(transport: str = 'rest'): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_instance(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.DeleteInstanceRequest( - name='name_value', + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_instance( + cloud_redis.UpdateInstanceRequest(), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + instance=cloud_redis.Instance(name='name_value'), ) -def test_delete_instance_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: client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) # Should wrap all calls on client creation @@ -4021,15 +3404,15 @@ def test_delete_instance_use_cached_wrapped_rpc(): 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_instance] = mock_rpc + request = {} client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() client.delete_instance(request) @@ -4038,172 +3421,123 @@ def test_delete_instance_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_instance_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 = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +def test_delete_instance_rest_required_fields(request_type=cloud_redis.DeleteInstanceRequest): + transport_class = transports.CloudRedisRestTransport - # Ensure method has been cached - assert client._client._transport.delete_instance in client._client._transport._wrapped_methods + 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 + )) - # 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_instance] = mock_rpc + # verify fields with default values are dropped - request = {} - await client.delete_instance(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 underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # verify required fields with default values are now present - # 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() + jsonified_request["name"] = 'name_value' - await client.delete_instance(request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' -@pytest.mark.asyncio -async def test_delete_instance_async(transport: str = 'grpc_asyncio', request_type=cloud_redis.DeleteInstanceRequest): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', ) + request = request_type(**request_init) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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') - ) - response = await client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = cloud_redis.DeleteInstanceRequest() - 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_delete_instance_async_from_dict(): - await test_delete_instance_async(request_type=dict) - -def test_delete_instance_field_headers(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.DeleteInstanceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + # 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': "delete", + 'query_params': 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_delete_instance_field_headers_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - ) + 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"} - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.DeleteInstanceRequest() + response = client.delete_instance(request) - request.name = 'name_value' + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_instance(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request +def test_delete_instance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) -def test_delete_instance_flattened(): +def test_delete_instance_rest_flattened(): client = CloudRedisClient( 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.delete_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_instance( + # 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 = {'name': 'projects/sample1/locations/sample2/instances/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 = 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_instance(**mock_args) # 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 + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, args[1]) -def test_delete_instance_flattened_error(): +def test_delete_instance_rest_flattened_error(transport: str = 'rest'): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Attempting to call a method with both a request object and flattened @@ -4214,5634 +3548,1600 @@ def test_delete_instance_flattened_error(): name='name_value', ) -@pytest.mark.asyncio -async def test_delete_instance_flattened_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = 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.delete_instance( - name='name_value', +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_instance_flattened_error_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. with pytest.raises(ValueError): - await client.delete_instance( - cloud_redis.DeleteInstanceRequest(), - name='name_value', + client = CloudRedisClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, ) - -@pytest.mark.parametrize("request_type", [ - cloud_redis.RescheduleMaintenanceRequest, - dict, -]) -def test_reschedule_maintenance(request_type, transport: str = 'grpc'): - client = CloudRedisClient( + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudRedisGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudRedisClient( + client_options=options, + transport=transport, + ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.reschedule_maintenance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.reschedule_maintenance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = cloud_redis.RescheduleMaintenanceRequest() - assert args[0] == request + # 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 = CloudRedisClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + # It is an error to provide scopes and a transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudRedisClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) -def test_reschedule_maintenance_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 = CloudRedisClient( +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudRedisGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', ) + client = CloudRedisClient(transport=transport) + assert client.transport is 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 = cloud_redis.RescheduleMaintenanceRequest( - name='name_value', +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), ) + channel = transport.grpc_channel + assert channel - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.reschedule_maintenance), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.reschedule_maintenance(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.RescheduleMaintenanceRequest( - name='name_value', - ) - -def test_reschedule_maintenance_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 = CloudRedisClient( - 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.reschedule_maintenance 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.reschedule_maintenance] = mock_rpc - request = {} - client.reschedule_maintenance(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.reschedule_maintenance(request) + transport = transports.CloudRedisGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel - # 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.parametrize("transport_class", [ + transports.CloudRedisGrpcTransport, + transports.CloudRedisGrpcAsyncIOTransport, + transports.CloudRedisRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() -@pytest.mark.asyncio -async def test_reschedule_maintenance_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 = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) +def test_transport_kind_grpc(): + transport = CloudRedisClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "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._client._transport.reschedule_maintenance in client._client._transport._wrapped_methods +def test_initialize_client_w_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.reschedule_maintenance] = mock_rpc - request = {} - await client.reschedule_maintenance(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_list_instances_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = cloud_redis.ListInstancesResponse() + client.list_instances(request=None) - # 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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ListInstancesRequest() - await client.reschedule_maintenance(request) + assert args[0] == request_msg - # 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_reschedule_maintenance_async(transport: str = 'grpc_asyncio', request_type=cloud_redis.RescheduleMaintenanceRequest): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, +# 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 = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. + # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.reschedule_maintenance), + type(client.transport.get_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') - ) - response = await client.reschedule_maintenance(request) + call.return_value = cloud_redis.Instance() + client.get_instance(request=None) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) + # Establish that the underlying stub method was called. + call.assert_called() _, args, _ = call.mock_calls[0] - request = cloud_redis.RescheduleMaintenanceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + request_msg = cloud_redis.GetInstanceRequest() + assert args[0] == request_msg -@pytest.mark.asyncio -async def test_reschedule_maintenance_async_from_dict(): - await test_reschedule_maintenance_async(request_type=dict) -def test_reschedule_maintenance_field_headers(): +# 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 = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.RescheduleMaintenanceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. + # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.reschedule_maintenance), + type(client.transport.create_instance), '__call__') as call: call.return_value = operations_pb2.Operation(name='operations/op') - client.reschedule_maintenance(request) + client.create_instance(request=None) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 + # Establish that the underlying stub method was called. + call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == request + request_msg = cloud_redis.CreateInstanceRequest() - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + assert args[0] == request_msg -@pytest.mark.asyncio -async def test_reschedule_maintenance_field_headers_async(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), +# 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 = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_redis.RescheduleMaintenanceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. + # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.reschedule_maintenance), + type(client.transport.update_instance), '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.reschedule_maintenance(request) + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_instance(request=None) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) + # Establish that the underlying stub method was called. + call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == request + request_msg = cloud_redis.UpdateInstanceRequest() - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + assert args[0] == request_msg -def test_reschedule_maintenance_flattened(): +# 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 = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Mock the actual call within the gRPC stub, and fake the request. + # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.reschedule_maintenance), + type(client.transport.delete_instance), '__call__') as call: - # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.reschedule_maintenance( - name='name_value', - reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), - ) + client.delete_instance(request=None) - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 + # Establish that the underlying stub method was called. + call.assert_called() _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].reschedule_type - mock_val = cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].schedule_time) == timestamp_pb2.Timestamp(seconds=751) + request_msg = cloud_redis.DeleteInstanceRequest() + assert args[0] == request_msg -def test_reschedule_maintenance_flattened_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), + +def test_transport_kind_grpc_asyncio(): + transport = CloudRedisAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) + assert transport.kind == "grpc_asyncio" - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.reschedule_maintenance( - cloud_redis.RescheduleMaintenanceRequest(), - name='name_value', - reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), - ) +def test_initialize_client_w_grpc_asyncio(): + client = CloudRedisAsyncClient( + 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_reschedule_maintenance_flattened_async(): +async def test_list_instances_empty_call_grpc_asyncio(): client = CloudRedisAsyncClient( credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # Mock the actual call within the gRPC stub, and fake the request. + # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.reschedule_maintenance), + type(client.transport.list_instances), '__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(cloud_redis.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_instances(request=None) - 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.reschedule_maintenance( - name='name_value', - reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) + # Establish that the underlying stub method was called. + call.assert_called() _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].reschedule_type - mock_val = cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].schedule_time) == timestamp_pb2.Timestamp(seconds=751) + request_msg = cloud_redis.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_reschedule_maintenance_flattened_error_async(): +async def test_get_instance_empty_call_grpc_asyncio(): client = CloudRedisAsyncClient( credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.reschedule_maintenance( - cloud_redis.RescheduleMaintenanceRequest(), + # 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(cloud_redis.Instance( name='name_value', - reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), - ) + display_name='display_name_value', + location_id='location_id_value', + alternative_location_id='alternative_location_id_value', + redis_version='redis_version_value', + reserved_ip_range='reserved_ip_range_value', + secondary_ip_range='secondary_ip_range_value', + host='host_value', + port=453, + current_location_id='current_location_id_value', + state=cloud_redis.Instance.State.CREATING, + status_message='status_message_value', + tier=cloud_redis.Instance.Tier.BASIC, + memory_size_gb=1499, + authorized_network='authorized_network_value', + persistence_iam_identity='persistence_iam_identity_value', + connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, + auth_enabled=True, + transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, + replica_count=1384, + read_endpoint='read_endpoint_value', + read_endpoint_port=1920, + read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, + customer_managed_key='customer_managed_key_value', + suspension_reasons=[cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE], + maintenance_version='maintenance_version_value', + available_maintenance_versions=['available_maintenance_versions_value'], + )) + await client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceRequest() + assert args[0] == request_msg -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: - client = CloudRedisClient( - 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_create_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - # Ensure method has been cached - assert client._transport.list_instances in client._transport._wrapped_methods + # 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) - # 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 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.CreateInstanceRequest() - request = {} - client.list_instances(request) + assert args[0] == request_msg - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - client.list_instances(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_update_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + 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.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.update_instance(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpdateInstanceRequest() -def test_list_instances_rest_required_fields(request_type=cloud_redis.ListInstancesRequest): - transport_class = transports.CloudRedisRestTransport + 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. +@pytest.mark.asyncio +async def test_delete_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_instances._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.delete_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.delete_instance(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 = cloud_redis.DeleteInstanceRequest() - jsonified_request["parent"] = 'parent_value' + assert args[0] == request_msg - 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_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' +def test_transport_kind_rest(): + transport = CloudRedisClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + +def test_list_instances_rest_bad_request(request_type=cloud_redis.ListInstancesRequest): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest" ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = cloud_redis.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 - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = cloud_redis.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) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_instances_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_instances._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + # 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) -def test_list_instances_rest_flattened(): +@pytest.mark.parametrize("request_type", [ + cloud_redis.ListInstancesRequest, + dict, +]) +def test_list_instances_rest_call_success(request_type): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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 = cloud_redis.ListInstancesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) - # get truthy value for each flattened field - mock_args = dict( - parent='parent_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 = cloud_redis.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], ) - mock_args.update(sample_request) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type return_value = cloud_redis.ListInstancesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + 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) - client.list_instances(**mock_args) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_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/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, args[1]) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) -def test_list_instances_rest_flattened_error(transport: str = 'rest'): + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.CloudRedisRestInterceptor, "post_list_instances") as post, \ + mock.patch.object(transports.CloudRedisRestInterceptor, "pre_list_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.ListInstancesRequest.pb(cloud_redis.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 = cloud_redis.ListInstancesResponse.to_json(cloud_redis.ListInstancesResponse()) + req.return_value.content = return_value + + request = cloud_redis.ListInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis.ListInstancesResponse() + + client.list_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request(request_type=cloud_redis.GetInstanceRequest): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest" ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request = request_type(**request_init) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_instances( - cloud_redis.ListInstancesRequest(), - parent='parent_value', - ) + # 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) -def test_list_instances_rest_pager(transport: str = 'rest'): +@pytest.mark.parametrize("request_type", [ + cloud_redis.GetInstanceRequest, + dict, +]) +def test_get_instance_rest_call_success(request_type): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest" ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request = request_type(**request_init) + # 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 = ( - cloud_redis.ListInstancesResponse( - instances=[ - cloud_redis.Instance(), - cloud_redis.Instance(), - cloud_redis.Instance(), - ], - next_page_token='abc', - ), - cloud_redis.ListInstancesResponse( - instances=[], - next_page_token='def', - ), - cloud_redis.ListInstancesResponse( - instances=[ - cloud_redis.Instance(), - ], - next_page_token='ghi', - ), - cloud_redis.ListInstancesResponse( - instances=[ - cloud_redis.Instance(), - cloud_redis.Instance(), - ], - ), + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = cloud_redis.Instance( + name='name_value', + display_name='display_name_value', + location_id='location_id_value', + alternative_location_id='alternative_location_id_value', + redis_version='redis_version_value', + reserved_ip_range='reserved_ip_range_value', + secondary_ip_range='secondary_ip_range_value', + host='host_value', + port=453, + current_location_id='current_location_id_value', + state=cloud_redis.Instance.State.CREATING, + status_message='status_message_value', + tier=cloud_redis.Instance.Tier.BASIC, + memory_size_gb=1499, + authorized_network='authorized_network_value', + persistence_iam_identity='persistence_iam_identity_value', + connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, + auth_enabled=True, + transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, + replica_count=1384, + read_endpoint='read_endpoint_value', + read_endpoint_port=1920, + read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, + customer_managed_key='customer_managed_key_value', + suspension_reasons=[cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE], + maintenance_version='maintenance_version_value', + available_maintenance_versions=['available_maintenance_versions_value'], ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(cloud_redis.ListInstancesResponse.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/locations/sample2'} - pager = client.list_instances(request=sample_request) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, cloud_redis.Instance) - for i in results) + # Convert return value to protobuf type + return_value = cloud_redis.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) - pages = list(client.list_instances(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_redis.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.location_id == 'location_id_value' + assert response.alternative_location_id == 'alternative_location_id_value' + assert response.redis_version == 'redis_version_value' + assert response.reserved_ip_range == 'reserved_ip_range_value' + assert response.secondary_ip_range == 'secondary_ip_range_value' + assert response.host == 'host_value' + assert response.port == 453 + assert response.current_location_id == 'current_location_id_value' + assert response.state == cloud_redis.Instance.State.CREATING + assert response.status_message == 'status_message_value' + assert response.tier == cloud_redis.Instance.Tier.BASIC + assert response.memory_size_gb == 1499 + assert response.authorized_network == 'authorized_network_value' + assert response.persistence_iam_identity == 'persistence_iam_identity_value' + assert response.connect_mode == cloud_redis.Instance.ConnectMode.DIRECT_PEERING + assert response.auth_enabled is True + assert response.transit_encryption_mode == cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION + assert response.replica_count == 1384 + assert response.read_endpoint == 'read_endpoint_value' + assert response.read_endpoint_port == 1920 + assert response.read_replicas_mode == cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED + assert response.customer_managed_key == 'customer_managed_key_value' + assert response.suspension_reasons == [cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE] + assert response.maintenance_version == 'maintenance_version_value' + assert response.available_maintenance_versions == ['available_maintenance_versions_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: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), ) + client = CloudRedisClient(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._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.get_instance] = mock_rpc - - request = {} - client.get_instance(request) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.CloudRedisRestInterceptor, "post_get_instance") as post, \ + mock.patch.object(transports.CloudRedisRestInterceptor, "pre_get_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.GetInstanceRequest.pb(cloud_redis.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + 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 = cloud_redis.Instance.to_json(cloud_redis.Instance()) + req.return_value.content = return_value - client.get_instance(request) + request = cloud_redis.GetInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis.Instance() - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + pre.assert_called_once() + post.assert_called_once() -def test_get_instance_rest_required_fields(request_type=cloud_redis.GetInstanceRequest): - transport_class = transports.CloudRedisRestTransport - request_init = {} - request_init["name"] = "" +def test_create_instance_rest_bad_request(request_type=cloud_redis.CreateInstanceRequest): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} 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_instance._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_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # 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) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' +@pytest.mark.parametrize("request_type", [ + cloud_redis.CreateInstanceRequest, + dict, +]) +def test_create_instance_rest_call_success(request_type): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest" ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = cloud_redis.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 - response_value = Response() - response_value.status_code = 200 + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'labels': {}, 'location_id': 'location_id_value', 'alternative_location_id': 'alternative_location_id_value', 'redis_version': 'redis_version_value', 'reserved_ip_range': 'reserved_ip_range_value', 'secondary_ip_range': 'secondary_ip_range_value', 'host': 'host_value', 'port': 453, 'current_location_id': 'current_location_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'state': 1, 'status_message': 'status_message_value', 'redis_configs': {}, 'tier': 1, 'memory_size_gb': 1499, 'authorized_network': 'authorized_network_value', 'persistence_iam_identity': 'persistence_iam_identity_value', 'connect_mode': 1, 'auth_enabled': True, 'server_ca_certs': [{'serial_number': 'serial_number_value', 'cert': 'cert_value', 'create_time': {}, 'expire_time': {}, 'sha1_fingerprint': 'sha1_fingerprint_value'}], 'transit_encryption_mode': 1, 'maintenance_policy': {'create_time': {}, 'update_time': {}, 'description': 'description_value', 'weekly_maintenance_window': [{'day': 1, 'start_time': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'duration': {'seconds': 751, 'nanos': 543}}]}, 'maintenance_schedule': {'start_time': {}, 'end_time': {}, 'can_reschedule': True, 'schedule_deadline_time': {}}, 'replica_count': 1384, 'nodes': [{'id': 'id_value', 'zone': 'zone_value'}], 'read_endpoint': 'read_endpoint_value', 'read_endpoint_port': 1920, 'read_replicas_mode': 1, 'customer_managed_key': 'customer_managed_key_value', 'persistence_config': {'persistence_mode': 1, 'rdb_snapshot_period': 3, 'rdb_next_snapshot_time': {}, 'rdb_snapshot_start_time': {}}, 'suspension_reasons': [1], 'maintenance_version': 'maintenance_version_value', 'available_maintenance_versions': ['available_maintenance_versions_value1', 'available_maintenance_versions_value2']} + # 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 - # Convert return value to protobuf type - return_value = cloud_redis.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis.CreateInstanceRequest.meta.fields["instance"] - 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"} + 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 = [] - response = client.get_instance(request) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params + 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) + ] -def test_get_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) + subfields_not_in_runtime = [] - unset_fields = transport.get_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + # 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} + ) -def test_get_instance_rest_flattened(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # 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 = cloud_redis.Instance() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis.Instance.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + 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) - 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/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, args[1]) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) -def test_get_instance_rest_flattened_error(transport: str = 'rest'): - client = CloudRedisClient( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( 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_instance( - cloud_redis.GetInstanceRequest(), - name='name_value', + interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), ) + client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_create_instance") as post, \ + mock.patch.object(transports.CloudRedisRestInterceptor, "pre_create_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.CreateInstanceRequest.pb(cloud_redis.CreateInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -def test_get_instance_auth_string_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 = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + 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 - # Ensure method has been cached - assert client._transport.get_instance_auth_string 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_auth_string] = mock_rpc - - request = {} - client.get_instance_auth_string(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_instance_auth_string(request) + request = cloud_redis.CreateInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + client.create_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + pre.assert_called_once() + post.assert_called_once() -def test_get_instance_auth_string_rest_required_fields(request_type=cloud_redis.GetInstanceAuthStringRequest): - transport_class = transports.CloudRedisRestTransport - request_init = {} - request_init["name"] = "" +def test_update_instance_rest_bad_request(request_type=cloud_redis.UpdateInstanceRequest): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'instance': {'name': 'projects/sample1/locations/sample2/instances/sample3'}} 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_instance_auth_string._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_instance_auth_string._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # 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) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' +@pytest.mark.parametrize("request_type", [ + cloud_redis.UpdateInstanceRequest, + dict, +]) +def test_update_instance_rest_call_success(request_type): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest" ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = cloud_redis.InstanceAuthString() - # 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 + # send a request that will satisfy transcoding + request_init = {'instance': {'name': 'projects/sample1/locations/sample2/instances/sample3'}} + request_init["instance"] = {'name': 'projects/sample1/locations/sample2/instances/sample3', 'display_name': 'display_name_value', 'labels': {}, 'location_id': 'location_id_value', 'alternative_location_id': 'alternative_location_id_value', 'redis_version': 'redis_version_value', 'reserved_ip_range': 'reserved_ip_range_value', 'secondary_ip_range': 'secondary_ip_range_value', 'host': 'host_value', 'port': 453, 'current_location_id': 'current_location_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'state': 1, 'status_message': 'status_message_value', 'redis_configs': {}, 'tier': 1, 'memory_size_gb': 1499, 'authorized_network': 'authorized_network_value', 'persistence_iam_identity': 'persistence_iam_identity_value', 'connect_mode': 1, 'auth_enabled': True, 'server_ca_certs': [{'serial_number': 'serial_number_value', 'cert': 'cert_value', 'create_time': {}, 'expire_time': {}, 'sha1_fingerprint': 'sha1_fingerprint_value'}], 'transit_encryption_mode': 1, 'maintenance_policy': {'create_time': {}, 'update_time': {}, 'description': 'description_value', 'weekly_maintenance_window': [{'day': 1, 'start_time': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'duration': {'seconds': 751, 'nanos': 543}}]}, 'maintenance_schedule': {'start_time': {}, 'end_time': {}, 'can_reschedule': True, 'schedule_deadline_time': {}}, 'replica_count': 1384, 'nodes': [{'id': 'id_value', 'zone': 'zone_value'}], 'read_endpoint': 'read_endpoint_value', 'read_endpoint_port': 1920, 'read_replicas_mode': 1, 'customer_managed_key': 'customer_managed_key_value', 'persistence_config': {'persistence_mode': 1, 'rdb_snapshot_period': 3, 'rdb_next_snapshot_time': {}, 'rdb_snapshot_start_time': {}}, 'suspension_reasons': [1], 'maintenance_version': 'maintenance_version_value', 'available_maintenance_versions': ['available_maintenance_versions_value1', 'available_maintenance_versions_value2']} + # 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 - # Convert return value to protobuf type - return_value = cloud_redis.InstanceAuthString.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis.UpdateInstanceRequest.meta.fields["instance"] - 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"} + 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 = [] - response = client.get_instance_auth_string(request) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params + 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) + ] -def test_get_instance_auth_string_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) + subfields_not_in_runtime = [] - unset_fields = transport.get_instance_auth_string._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + # 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} + ) -def test_get_instance_auth_string_rest_flattened(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # 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 = cloud_redis.InstanceAuthString() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis.InstanceAuthString.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + 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) - client.get_instance_auth_string(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/instances/*}/authString" % client.transport._host, args[1]) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) -def test_get_instance_auth_string_rest_flattened_error(transport: str = 'rest'): - client = CloudRedisClient( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( 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_instance_auth_string( - cloud_redis.GetInstanceAuthStringRequest(), - name='name_value', + interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), ) + client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_update_instance") as post, \ + mock.patch.object(transports.CloudRedisRestInterceptor, "pre_update_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.UpdateInstanceRequest.pb(cloud_redis.UpdateInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -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: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + 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 - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + request = cloud_redis.UpdateInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - # Ensure method has been cached - assert client._transport.create_instance in client._transport._wrapped_methods + client.update_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - # 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 + pre.assert_called_once() + post.assert_called_once() - request = {} - client.create_instance(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 +def test_delete_instance_rest_bad_request(request_type=cloud_redis.DeleteInstanceRequest): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request = request_type(**request_init) - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + # 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) - 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 +@pytest.mark.parametrize("request_type", [ + cloud_redis.DeleteInstanceRequest, + dict, +]) +def test_delete_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request = request_type(**request_init) -def test_create_instance_rest_required_fields(request_type=cloud_redis.CreateInstanceRequest): - transport_class = transports.CloudRedisRestTransport + # 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') - 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 - )) + # 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.delete_instance(request) - # verify fields with default values are dropped - assert "instanceId" not in jsonified_request + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) - jsonified_request["parent"] = 'parent_value' - jsonified_request["instanceId"] = 'instance_id_value' + 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.CloudRedisRestInterceptor, "post_delete_instance") as post, \ + mock.patch.object(transports.CloudRedisRestInterceptor, "pre_delete_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.DeleteInstanceRequest.pb(cloud_redis.DeleteInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("instance_id", )) - jsonified_request.update(unset_fields) + 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 - # 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' + request = cloud_redis.DeleteInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) - request = request_type(**request_init) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - # 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 BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) # 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 + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # 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') - 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"} + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_instance(request) + response = client.get_location(request) - expected_params = [ - ( - "instanceId", - "", - ), - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) -def test_create_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) - unset_fields = transport.create_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(("instanceId", )) & set(("parent", "instanceId", "instance", ))) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) -def test_create_instance_rest_flattened(): +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request_init = {'name': '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: + with mock.patch.object(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/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - instance_id='instance_id_value', - instance=cloud_redis.Instance(name='name_value'), - ) - mock_args.update(sample_request) + return_value = locations_pb2.ListLocationsResponse() # Wrap the value into a proper Response obj - response_value = Response() + 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') + 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_instance(**mock_args) + response = client.list_locations(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/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, args[1]) + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) -def test_create_instance_rest_flattened_error(transport: str = 'rest'): +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_instance( - cloud_redis.CreateInstanceRequest(), - parent='parent_value', - instance_id='instance_id_value', - instance=cloud_redis.Instance(name='name_value'), - ) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) -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 = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None - # Ensure method has been cached - assert client._transport.update_instance in client._transport._wrapped_methods + # 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') - # 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_instance] = mock_rpc + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - request = {} - client.update_instance(request) + response = client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the response is the type that we expect. + assert response is None - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - client.update_instance(request) +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - # 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 http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) -def test_update_instance_rest_required_fields(request_type=cloud_redis.UpdateInstanceRequest): - transport_class = transports.CloudRedisRestTransport +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - request_init = {} + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} 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 http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None - # verify fields with default values are dropped + # 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') - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # verify required fields with default values are now present + response = client.delete_operation(request) - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).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 response is the type that we expect. + assert response is None - # verify required fields with non-default values are left alone +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) - request = request_type(**request_init) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - # 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 BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) # 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 + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # 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') - 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"} + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_instance(request) + response = client.get_operation(request) - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_update_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - unset_fields = transport.update_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", "instance", ))) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) -def test_update_instance_rest_flattened(): +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request_init = {'name': 'projects/sample1/locations/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: + with mock.patch.object(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/locations/sample2/instances/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - instance=cloud_redis.Instance(name='name_value'), - ) - mock_args.update(sample_request) + return_value = operations_pb2.ListOperationsResponse() # Wrap the value into a proper Response obj - response_value = Response() + 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') + 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_instance(**mock_args) + response = client.list_operations(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/v1/{instance.name=projects/*/locations/*/instances/*}" % client.transport._host, args[1]) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_update_instance_rest_flattened_error(transport: str = 'rest'): +def test_wait_operation_rest_bad_request(request_type=operations_pb2.WaitOperationRequest): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_instance( - cloud_redis.UpdateInstanceRequest(), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - instance=cloud_redis.Instance(name='name_value'), - ) - - -def test_upgrade_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 = CloudRedisClient( - 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.upgrade_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.upgrade_instance] = mock_rpc + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.wait_operation(request) - request = {} - client.upgrade_instance(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 +@pytest.mark.parametrize("request_type", [ + operations_pb2.WaitOperationRequest, + dict, +]) +def test_wait_operation_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() - client.upgrade_instance(request) + # 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') - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.wait_operation(request) -def test_upgrade_instance_rest_required_fields(request_type=cloud_redis.UpgradeInstanceRequest): - transport_class = transports.CloudRedisRestTransport + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) - request_init = {} - request_init["name"] = "" - request_init["redis_version"] = "" - 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_initialize_client_w_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None - # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).upgrade_instance._get_unset_required_fields(jsonified_request) - 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. +def test_list_instances_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # verify required fields with default values are now present + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + client.list_instances(request=None) - jsonified_request["name"] = 'name_value' - jsonified_request["redisVersion"] = 'redis_version_value' + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ListInstancesRequest() - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).upgrade_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + assert args[0] == request_msg - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "redisVersion" in jsonified_request - assert jsonified_request["redisVersion"] == 'redis_version_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_instance_empty_call_rest(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + 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 + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + client.get_instance(request=None) - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceRequest() - 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 - response = client.upgrade_instance(request) - expected_params = [ - ] - 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_create_instance_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + client.create_instance(request=None) -def test_upgrade_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.CreateInstanceRequest() - unset_fields = transport.upgrade_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "redisVersion", ))) + assert args[0] == request_msg -def test_upgrade_instance_rest_flattened(): +# 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_rest(): client = CloudRedisClient( 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 = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - redis_version='redis_version_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"} + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__call__') as call: + client.update_instance(request=None) - client.upgrade_instance(**mock_args) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpdateInstanceRequest() - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/instances/*}:upgrade" % client.transport._host, args[1]) + assert args[0] == request_msg -def test_upgrade_instance_rest_flattened_error(transport: str = 'rest'): +# 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_rest(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.upgrade_instance( - cloud_redis.UpgradeInstanceRequest(), - name='name_value', - redis_version='redis_version_value', - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + client.delete_instance(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.DeleteInstanceRequest() -def test_import_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 = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + assert args[0] == request_msg - # 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.import_instance in client._transport._wrapped_methods +def test_cloud_redis_rest_lro_client(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport - # 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.import_instance] = mock_rpc - - request = {} - client.import_instance(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.import_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_import_instance_rest_required_fields(request_type=cloud_redis.ImportInstanceRequest): - transport_class = transports.CloudRedisRestTransport - - 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()).import_instance._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()).import_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' - - client = CloudRedisClient( - 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.import_instance(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "inputConfig", ))) - - -def test_import_instance_rest_flattened(): - client = CloudRedisClient( - 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 = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - input_config=cloud_redis.InputConfig(gcs_source=cloud_redis.GcsSource(uri='uri_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.import_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/v1/{name=projects/*/locations/*/instances/*}:import" % client.transport._host, args[1]) - - -def test_import_instance_rest_flattened_error(transport: str = 'rest'): - client = CloudRedisClient( - 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.import_instance( - cloud_redis.ImportInstanceRequest(), - name='name_value', - input_config=cloud_redis.InputConfig(gcs_source=cloud_redis.GcsSource(uri='uri_value')), - ) - - -def test_export_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 = CloudRedisClient( - 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.export_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.export_instance] = mock_rpc - - request = {} - client.export_instance(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.export_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_export_instance_rest_required_fields(request_type=cloud_redis.ExportInstanceRequest): - transport_class = transports.CloudRedisRestTransport - - 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()).export_instance._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()).export_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' - - client = CloudRedisClient( - 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.export_instance(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_export_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.export_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "outputConfig", ))) - - -def test_export_instance_rest_flattened(): - client = CloudRedisClient( - 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 = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - output_config=cloud_redis.OutputConfig(gcs_destination=cloud_redis.GcsDestination(uri='uri_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.export_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/v1/{name=projects/*/locations/*/instances/*}:export" % client.transport._host, args[1]) - - -def test_export_instance_rest_flattened_error(transport: str = 'rest'): - client = CloudRedisClient( - 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.export_instance( - cloud_redis.ExportInstanceRequest(), - name='name_value', - output_config=cloud_redis.OutputConfig(gcs_destination=cloud_redis.GcsDestination(uri='uri_value')), - ) - - -def test_failover_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 = CloudRedisClient( - 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.failover_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.failover_instance] = mock_rpc - - request = {} - client.failover_instance(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.failover_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_failover_instance_rest_required_fields(request_type=cloud_redis.FailoverInstanceRequest): - transport_class = transports.CloudRedisRestTransport - - 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()).failover_instance._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()).failover_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' - - client = CloudRedisClient( - 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.failover_instance(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_failover_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.failover_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_failover_instance_rest_flattened(): - client = CloudRedisClient( - 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 = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, - ) - 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.failover_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/v1/{name=projects/*/locations/*/instances/*}:failover" % client.transport._host, args[1]) - - -def test_failover_instance_rest_flattened_error(transport: str = 'rest'): - client = CloudRedisClient( - 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.failover_instance( - cloud_redis.FailoverInstanceRequest(), - name='name_value', - data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, - ) - - -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 = CloudRedisClient( - 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_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_instance] = mock_rpc - - request = {} - client.delete_instance(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.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_delete_instance_rest_required_fields(request_type=cloud_redis.DeleteInstanceRequest): - transport_class = transports.CloudRedisRestTransport - - 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_instance._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_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' - - client = CloudRedisClient( - 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': "delete", - 'query_params': 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.delete_instance(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_instance_rest_flattened(): - client = CloudRedisClient( - 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 = {'name': 'projects/sample1/locations/sample2/instances/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 = 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_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/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, args[1]) - - -def test_delete_instance_rest_flattened_error(transport: str = 'rest'): - client = CloudRedisClient( - 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( - cloud_redis.DeleteInstanceRequest(), - name='name_value', - ) - - -def test_reschedule_maintenance_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 = CloudRedisClient( - 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.reschedule_maintenance 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.reschedule_maintenance] = mock_rpc - - request = {} - client.reschedule_maintenance(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.reschedule_maintenance(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_reschedule_maintenance_rest_required_fields(request_type=cloud_redis.RescheduleMaintenanceRequest): - transport_class = transports.CloudRedisRestTransport - - 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()).reschedule_maintenance._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()).reschedule_maintenance._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 = CloudRedisClient( - 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.reschedule_maintenance(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_reschedule_maintenance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.reschedule_maintenance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "rescheduleType", ))) - - -def test_reschedule_maintenance_rest_flattened(): - client = CloudRedisClient( - 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 = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), - ) - 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.reschedule_maintenance(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance" % client.transport._host, args[1]) - - -def test_reschedule_maintenance_rest_flattened_error(transport: str = 'rest'): - client = CloudRedisClient( - 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.reschedule_maintenance( - cloud_redis.RescheduleMaintenanceRequest(), - name='name_value', - reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudRedisClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudRedisClient( - 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 = CloudRedisClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudRedisClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CloudRedisClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CloudRedisGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CloudRedisGrpcTransport, - transports.CloudRedisGrpcAsyncIOTransport, - transports.CloudRedisRestTransport, -]) -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 = CloudRedisClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = CloudRedisClient( - 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_list_instances_empty_call_grpc(): - client = CloudRedisClient( - 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 = cloud_redis.ListInstancesResponse() - client.list_instances(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.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_get_instance_empty_call_grpc(): - client = CloudRedisClient( - 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 = cloud_redis.Instance() - client.get_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.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_get_instance_auth_string_empty_call_grpc(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), - '__call__') as call: - call.return_value = cloud_redis.InstanceAuthString() - client.get_instance_auth_string(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.GetInstanceAuthStringRequest() - - 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_instance_empty_call_grpc(): - client = CloudRedisClient( - 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 = cloud_redis.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_update_instance_empty_call_grpc(): - client = CloudRedisClient( - 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 = operations_pb2.Operation(name='operations/op') - client.update_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.UpdateInstanceRequest() - - 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_upgrade_instance_empty_call_grpc(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.upgrade_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.UpgradeInstanceRequest() - - 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_import_instance_empty_call_grpc(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.ImportInstanceRequest() - - 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_export_instance_empty_call_grpc(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.ExportInstanceRequest() - - 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_failover_instance_empty_call_grpc(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.failover_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.FailoverInstanceRequest() - - 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 = CloudRedisClient( - 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 = operations_pb2.Operation(name='operations/op') - client.delete_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.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_reschedule_maintenance_empty_call_grpc(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.reschedule_maintenance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.reschedule_maintenance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.RescheduleMaintenanceRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = CloudRedisAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = CloudRedisAsyncClient( - 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_list_instances_empty_call_grpc_asyncio(): - client = CloudRedisAsyncClient( - 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(cloud_redis.ListInstancesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = cloud_redis.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_get_instance_empty_call_grpc_asyncio(): - client = CloudRedisAsyncClient( - 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(cloud_redis.Instance( - name='name_value', - display_name='display_name_value', - location_id='location_id_value', - alternative_location_id='alternative_location_id_value', - redis_version='redis_version_value', - reserved_ip_range='reserved_ip_range_value', - secondary_ip_range='secondary_ip_range_value', - host='host_value', - port=453, - current_location_id='current_location_id_value', - state=cloud_redis.Instance.State.CREATING, - status_message='status_message_value', - tier=cloud_redis.Instance.Tier.BASIC, - memory_size_gb=1499, - authorized_network='authorized_network_value', - persistence_iam_identity='persistence_iam_identity_value', - connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, - auth_enabled=True, - transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, - replica_count=1384, - read_endpoint='read_endpoint_value', - read_endpoint_port=1920, - read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, - customer_managed_key='customer_managed_key_value', - suspension_reasons=[cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE], - maintenance_version='maintenance_version_value', - available_maintenance_versions=['available_maintenance_versions_value'], - )) - await client.get_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.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_get_instance_auth_string_empty_call_grpc_asyncio(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(cloud_redis.InstanceAuthString( - auth_string='auth_string_value', - )) - await client.get_instance_auth_string(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.GetInstanceAuthStringRequest() - - 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_instance_empty_call_grpc_asyncio(): - client = CloudRedisAsyncClient( - 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 = cloud_redis.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_update_instance_empty_call_grpc_asyncio(): - client = CloudRedisAsyncClient( - 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( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.UpdateInstanceRequest() - - 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_upgrade_instance_empty_call_grpc_asyncio(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_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.upgrade_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.UpgradeInstanceRequest() - - 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_import_instance_empty_call_grpc_asyncio(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_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.import_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.ImportInstanceRequest() - - 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_export_instance_empty_call_grpc_asyncio(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_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.export_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.ExportInstanceRequest() - - 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_failover_instance_empty_call_grpc_asyncio(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.failover_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.failover_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.FailoverInstanceRequest() - - 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 = CloudRedisAsyncClient( - 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( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.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_reschedule_maintenance_empty_call_grpc_asyncio(): - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.reschedule_maintenance), - '__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.reschedule_maintenance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.RescheduleMaintenanceRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = CloudRedisClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_instances_rest_bad_request(request_type=cloud_redis.ListInstancesRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/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.list_instances(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.ListInstancesRequest, - dict, -]) -def test_list_instances_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/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 = cloud_redis.ListInstancesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = cloud_redis.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) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_list_instances") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_list_instances") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.ListInstancesRequest.pb(cloud_redis.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 = cloud_redis.ListInstancesResponse.to_json(cloud_redis.ListInstancesResponse()) - req.return_value.content = return_value - - request = cloud_redis.ListInstancesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.ListInstancesResponse() - - client.list_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_instance_rest_bad_request(request_type=cloud_redis.GetInstanceRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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_instance(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.GetInstanceRequest, - dict, -]) -def test_get_instance_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = cloud_redis.Instance( - name='name_value', - display_name='display_name_value', - location_id='location_id_value', - alternative_location_id='alternative_location_id_value', - redis_version='redis_version_value', - reserved_ip_range='reserved_ip_range_value', - secondary_ip_range='secondary_ip_range_value', - host='host_value', - port=453, - current_location_id='current_location_id_value', - state=cloud_redis.Instance.State.CREATING, - status_message='status_message_value', - tier=cloud_redis.Instance.Tier.BASIC, - memory_size_gb=1499, - authorized_network='authorized_network_value', - persistence_iam_identity='persistence_iam_identity_value', - connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, - auth_enabled=True, - transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, - replica_count=1384, - read_endpoint='read_endpoint_value', - read_endpoint_port=1920, - read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, - customer_managed_key='customer_managed_key_value', - suspension_reasons=[cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE], - maintenance_version='maintenance_version_value', - available_maintenance_versions=['available_maintenance_versions_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 = cloud_redis.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, cloud_redis.Instance) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.location_id == 'location_id_value' - assert response.alternative_location_id == 'alternative_location_id_value' - assert response.redis_version == 'redis_version_value' - assert response.reserved_ip_range == 'reserved_ip_range_value' - assert response.secondary_ip_range == 'secondary_ip_range_value' - assert response.host == 'host_value' - assert response.port == 453 - assert response.current_location_id == 'current_location_id_value' - assert response.state == cloud_redis.Instance.State.CREATING - assert response.status_message == 'status_message_value' - assert response.tier == cloud_redis.Instance.Tier.BASIC - assert response.memory_size_gb == 1499 - assert response.authorized_network == 'authorized_network_value' - assert response.persistence_iam_identity == 'persistence_iam_identity_value' - assert response.connect_mode == cloud_redis.Instance.ConnectMode.DIRECT_PEERING - assert response.auth_enabled is True - assert response.transit_encryption_mode == cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION - assert response.replica_count == 1384 - assert response.read_endpoint == 'read_endpoint_value' - assert response.read_endpoint_port == 1920 - assert response.read_replicas_mode == cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED - assert response.customer_managed_key == 'customer_managed_key_value' - assert response.suspension_reasons == [cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE] - assert response.maintenance_version == 'maintenance_version_value' - assert response.available_maintenance_versions == ['available_maintenance_versions_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_get_instance") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_get_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.GetInstanceRequest.pb(cloud_redis.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 = cloud_redis.Instance.to_json(cloud_redis.Instance()) - req.return_value.content = return_value - - request = cloud_redis.GetInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.Instance() - - client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_instance_auth_string_rest_bad_request(request_type=cloud_redis.GetInstanceAuthStringRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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_instance_auth_string(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.GetInstanceAuthStringRequest, - dict, -]) -def test_get_instance_auth_string_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = cloud_redis.InstanceAuthString( - auth_string='auth_string_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 = cloud_redis.InstanceAuthString.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_auth_string(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis.InstanceAuthString) - assert response.auth_string == 'auth_string_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_auth_string_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_get_instance_auth_string") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_get_instance_auth_string") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.GetInstanceAuthStringRequest.pb(cloud_redis.GetInstanceAuthStringRequest()) - 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 = cloud_redis.InstanceAuthString.to_json(cloud_redis.InstanceAuthString()) - req.return_value.content = return_value - - request = cloud_redis.GetInstanceAuthStringRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.InstanceAuthString() - - client.get_instance_auth_string(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_instance_rest_bad_request(request_type=cloud_redis.CreateInstanceRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/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_instance(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.CreateInstanceRequest, - dict, -]) -def test_create_instance_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'labels': {}, 'location_id': 'location_id_value', 'alternative_location_id': 'alternative_location_id_value', 'redis_version': 'redis_version_value', 'reserved_ip_range': 'reserved_ip_range_value', 'secondary_ip_range': 'secondary_ip_range_value', 'host': 'host_value', 'port': 453, 'current_location_id': 'current_location_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'state': 1, 'status_message': 'status_message_value', 'redis_configs': {}, 'tier': 1, 'memory_size_gb': 1499, 'authorized_network': 'authorized_network_value', 'persistence_iam_identity': 'persistence_iam_identity_value', 'connect_mode': 1, 'auth_enabled': True, 'server_ca_certs': [{'serial_number': 'serial_number_value', 'cert': 'cert_value', 'create_time': {}, 'expire_time': {}, 'sha1_fingerprint': 'sha1_fingerprint_value'}], 'transit_encryption_mode': 1, 'maintenance_policy': {'create_time': {}, 'update_time': {}, 'description': 'description_value', 'weekly_maintenance_window': [{'day': 1, 'start_time': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'duration': {'seconds': 751, 'nanos': 543}}]}, 'maintenance_schedule': {'start_time': {}, 'end_time': {}, 'can_reschedule': True, 'schedule_deadline_time': {}}, 'replica_count': 1384, 'nodes': [{'id': 'id_value', 'zone': 'zone_value'}], 'read_endpoint': 'read_endpoint_value', 'read_endpoint_port': 1920, 'read_replicas_mode': 1, 'customer_managed_key': 'customer_managed_key_value', 'persistence_config': {'persistence_mode': 1, 'rdb_snapshot_period': 3, 'rdb_next_snapshot_time': {}, 'rdb_snapshot_start_time': {}}, 'suspension_reasons': [1], 'maintenance_version': 'maintenance_version_value', 'available_maintenance_versions': ['available_maintenance_versions_value1', 'available_maintenance_versions_value2']} - # 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 = cloud_redis.CreateInstanceRequest.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.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.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_create_instance") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_create_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.CreateInstanceRequest.pb(cloud_redis.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 = cloud_redis.CreateInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_instance_rest_bad_request(request_type=cloud_redis.UpdateInstanceRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'instance': {'name': 'projects/sample1/locations/sample2/instances/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.update_instance(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.UpdateInstanceRequest, - dict, -]) -def test_update_instance_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'instance': {'name': 'projects/sample1/locations/sample2/instances/sample3'}} - request_init["instance"] = {'name': 'projects/sample1/locations/sample2/instances/sample3', 'display_name': 'display_name_value', 'labels': {}, 'location_id': 'location_id_value', 'alternative_location_id': 'alternative_location_id_value', 'redis_version': 'redis_version_value', 'reserved_ip_range': 'reserved_ip_range_value', 'secondary_ip_range': 'secondary_ip_range_value', 'host': 'host_value', 'port': 453, 'current_location_id': 'current_location_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'state': 1, 'status_message': 'status_message_value', 'redis_configs': {}, 'tier': 1, 'memory_size_gb': 1499, 'authorized_network': 'authorized_network_value', 'persistence_iam_identity': 'persistence_iam_identity_value', 'connect_mode': 1, 'auth_enabled': True, 'server_ca_certs': [{'serial_number': 'serial_number_value', 'cert': 'cert_value', 'create_time': {}, 'expire_time': {}, 'sha1_fingerprint': 'sha1_fingerprint_value'}], 'transit_encryption_mode': 1, 'maintenance_policy': {'create_time': {}, 'update_time': {}, 'description': 'description_value', 'weekly_maintenance_window': [{'day': 1, 'start_time': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'duration': {'seconds': 751, 'nanos': 543}}]}, 'maintenance_schedule': {'start_time': {}, 'end_time': {}, 'can_reschedule': True, 'schedule_deadline_time': {}}, 'replica_count': 1384, 'nodes': [{'id': 'id_value', 'zone': 'zone_value'}], 'read_endpoint': 'read_endpoint_value', 'read_endpoint_port': 1920, 'read_replicas_mode': 1, 'customer_managed_key': 'customer_managed_key_value', 'persistence_config': {'persistence_mode': 1, 'rdb_snapshot_period': 3, 'rdb_next_snapshot_time': {}, 'rdb_snapshot_start_time': {}}, 'suspension_reasons': [1], 'maintenance_version': 'maintenance_version_value', 'available_maintenance_versions': ['available_maintenance_versions_value1', 'available_maintenance_versions_value2']} - # 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 = cloud_redis.UpdateInstanceRequest.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.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_update_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_update_instance") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_update_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.UpdateInstanceRequest.pb(cloud_redis.UpdateInstanceRequest()) - 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 = cloud_redis.UpdateInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_upgrade_instance_rest_bad_request(request_type=cloud_redis.UpgradeInstanceRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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.upgrade_instance(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.UpgradeInstanceRequest, - dict, -]) -def test_upgrade_instance_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = 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.upgrade_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_upgrade_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_upgrade_instance") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_upgrade_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.UpgradeInstanceRequest.pb(cloud_redis.UpgradeInstanceRequest()) - 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 = cloud_redis.UpgradeInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.upgrade_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_instance_rest_bad_request(request_type=cloud_redis.ImportInstanceRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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.import_instance(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.ImportInstanceRequest, - dict, -]) -def test_import_instance_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = 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.import_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_import_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_import_instance") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_import_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.ImportInstanceRequest.pb(cloud_redis.ImportInstanceRequest()) - 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 = cloud_redis.ImportInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_instance_rest_bad_request(request_type=cloud_redis.ExportInstanceRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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.export_instance(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.ExportInstanceRequest, - dict, -]) -def test_export_instance_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = 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.export_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_export_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_export_instance") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_export_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.ExportInstanceRequest.pb(cloud_redis.ExportInstanceRequest()) - 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 = cloud_redis.ExportInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_failover_instance_rest_bad_request(request_type=cloud_redis.FailoverInstanceRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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.failover_instance(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.FailoverInstanceRequest, - dict, -]) -def test_failover_instance_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = 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.failover_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_failover_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_failover_instance") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_failover_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.FailoverInstanceRequest.pb(cloud_redis.FailoverInstanceRequest()) - 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 = cloud_redis.FailoverInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.failover_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_instance_rest_bad_request(request_type=cloud_redis.DeleteInstanceRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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_instance(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.DeleteInstanceRequest, - dict, -]) -def test_delete_instance_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = 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.delete_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_delete_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_delete_instance") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_delete_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.DeleteInstanceRequest.pb(cloud_redis.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"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = cloud_redis.DeleteInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_reschedule_maintenance_rest_bad_request(request_type=cloud_redis.RescheduleMaintenanceRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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.reschedule_maintenance(request) - - -@pytest.mark.parametrize("request_type", [ - cloud_redis.RescheduleMaintenanceRequest, - dict, -]) -def test_reschedule_maintenance_rest_call_success(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = 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.reschedule_maintenance(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_reschedule_maintenance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_reschedule_maintenance") as post, \ - mock.patch.object(transports.CloudRedisRestInterceptor, "pre_reschedule_maintenance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.RescheduleMaintenanceRequest.pb(cloud_redis.RescheduleMaintenanceRequest()) - 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 = cloud_redis.RescheduleMaintenanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.reschedule_maintenance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # 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.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # 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.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(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.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(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_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = 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.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = 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.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_wait_operation_rest_bad_request(request_type=operations_pb2.WaitOperationRequest): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.wait_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.WaitOperationRequest, - dict, -]) -def test_wait_operation_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = 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.wait_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_initialize_client_w_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - 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_list_instances_empty_call_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), - '__call__') as call: - client.list_instances(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.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_get_instance_empty_call_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - client.get_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.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_get_instance_auth_string_empty_call_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), - '__call__') as call: - client.get_instance_auth_string(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.GetInstanceAuthStringRequest() - - 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_instance_empty_call_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_instance), - '__call__') as call: - client.create_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.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_update_instance_empty_call_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_instance), - '__call__') as call: - client.update_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.UpdateInstanceRequest() - - 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_upgrade_instance_empty_call_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_instance), - '__call__') as call: - client.upgrade_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.UpgradeInstanceRequest() - - 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_import_instance_empty_call_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_instance), - '__call__') as call: - client.import_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.ImportInstanceRequest() - - 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_export_instance_empty_call_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_instance), - '__call__') as call: - client.export_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.ExportInstanceRequest() - - 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_failover_instance_empty_call_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), - '__call__') as call: - client.failover_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.FailoverInstanceRequest() - - 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_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - client.delete_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.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_reschedule_maintenance_empty_call_rest(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.reschedule_maintenance), - '__call__') as call: - client.reschedule_maintenance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.RescheduleMaintenanceRequest() - - assert args[0] == request_msg - - -def test_cloud_redis_rest_lro_client(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have an api-core operations client. - assert isinstance( - transport.operations_client, -operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - -def test_transport_kind_rest_asyncio(): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - transport = CloudRedisAsyncClient.get_transport_class("rest_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "rest_asyncio" - - -@pytest.mark.asyncio -async def test_list_instances_rest_asyncio_bad_request(request_type=cloud_redis.ListInstancesRequest): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(AsyncAuthorizedSession, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.read = mock.AsyncMock(return_value=b'{}') - 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"} - await client.list_instances(request) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("request_type", [ - cloud_redis.ListInstancesRequest, - dict, -]) -async def test_list_instances_rest_asyncio_call_success(request_type): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/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 = cloud_redis.ListInstancesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = cloud_redis.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.list_instances(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -@pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_list_instances_rest_asyncio_interceptors(null_interceptor): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - transport = transports.AsyncCloudRedisRestTransport( - credentials=async_anonymous_credentials(), - interceptor=None if null_interceptor else transports.AsyncCloudRedisRestInterceptor(), - ) - client = CloudRedisAsyncClient(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.AsyncCloudRedisRestInterceptor, "post_list_instances") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_list_instances") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.ListInstancesRequest.pb(cloud_redis.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 = cloud_redis.ListInstancesResponse.to_json(cloud_redis.ListInstancesResponse()) - req.return_value.read = mock.AsyncMock(return_value=return_value) - - request = cloud_redis.ListInstancesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.ListInstancesResponse() - - await client.list_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -@pytest.mark.asyncio -async def test_get_instance_rest_asyncio_bad_request(request_type=cloud_redis.GetInstanceRequest): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(AsyncAuthorizedSession, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.read = mock.AsyncMock(return_value=b'{}') - 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"} - await client.get_instance(request) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("request_type", [ - cloud_redis.GetInstanceRequest, - dict, -]) -async def test_get_instance_rest_asyncio_call_success(request_type): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = cloud_redis.Instance( - name='name_value', - display_name='display_name_value', - location_id='location_id_value', - alternative_location_id='alternative_location_id_value', - redis_version='redis_version_value', - reserved_ip_range='reserved_ip_range_value', - secondary_ip_range='secondary_ip_range_value', - host='host_value', - port=453, - current_location_id='current_location_id_value', - state=cloud_redis.Instance.State.CREATING, - status_message='status_message_value', - tier=cloud_redis.Instance.Tier.BASIC, - memory_size_gb=1499, - authorized_network='authorized_network_value', - persistence_iam_identity='persistence_iam_identity_value', - connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, - auth_enabled=True, - transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, - replica_count=1384, - read_endpoint='read_endpoint_value', - read_endpoint_port=1920, - read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, - customer_managed_key='customer_managed_key_value', - suspension_reasons=[cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE], - maintenance_version='maintenance_version_value', - available_maintenance_versions=['available_maintenance_versions_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 = cloud_redis.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.get_instance(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis.Instance) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.location_id == 'location_id_value' - assert response.alternative_location_id == 'alternative_location_id_value' - assert response.redis_version == 'redis_version_value' - assert response.reserved_ip_range == 'reserved_ip_range_value' - assert response.secondary_ip_range == 'secondary_ip_range_value' - assert response.host == 'host_value' - assert response.port == 453 - assert response.current_location_id == 'current_location_id_value' - assert response.state == cloud_redis.Instance.State.CREATING - assert response.status_message == 'status_message_value' - assert response.tier == cloud_redis.Instance.Tier.BASIC - assert response.memory_size_gb == 1499 - assert response.authorized_network == 'authorized_network_value' - assert response.persistence_iam_identity == 'persistence_iam_identity_value' - assert response.connect_mode == cloud_redis.Instance.ConnectMode.DIRECT_PEERING - assert response.auth_enabled is True - assert response.transit_encryption_mode == cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION - assert response.replica_count == 1384 - assert response.read_endpoint == 'read_endpoint_value' - assert response.read_endpoint_port == 1920 - assert response.read_replicas_mode == cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED - assert response.customer_managed_key == 'customer_managed_key_value' - assert response.suspension_reasons == [cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE] - assert response.maintenance_version == 'maintenance_version_value' - assert response.available_maintenance_versions == ['available_maintenance_versions_value'] - - -@pytest.mark.asyncio -@pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_get_instance_rest_asyncio_interceptors(null_interceptor): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - transport = transports.AsyncCloudRedisRestTransport( - credentials=async_anonymous_credentials(), - interceptor=None if null_interceptor else transports.AsyncCloudRedisRestInterceptor(), - ) - client = CloudRedisAsyncClient(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.AsyncCloudRedisRestInterceptor, "post_get_instance") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_get_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.GetInstanceRequest.pb(cloud_redis.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 = cloud_redis.Instance.to_json(cloud_redis.Instance()) - req.return_value.read = mock.AsyncMock(return_value=return_value) - - request = cloud_redis.GetInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.Instance() - - await client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -@pytest.mark.asyncio -async def test_get_instance_auth_string_rest_asyncio_bad_request(request_type=cloud_redis.GetInstanceAuthStringRequest): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(AsyncAuthorizedSession, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.read = mock.AsyncMock(return_value=b'{}') - 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"} - await client.get_instance_auth_string(request) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("request_type", [ - cloud_redis.GetInstanceAuthStringRequest, - dict, -]) -async def test_get_instance_auth_string_rest_asyncio_call_success(request_type): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = cloud_redis.InstanceAuthString( - auth_string='auth_string_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 = cloud_redis.InstanceAuthString.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.get_instance_auth_string(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis.InstanceAuthString) - assert response.auth_string == 'auth_string_value' - - -@pytest.mark.asyncio -@pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_get_instance_auth_string_rest_asyncio_interceptors(null_interceptor): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - transport = transports.AsyncCloudRedisRestTransport( - credentials=async_anonymous_credentials(), - interceptor=None if null_interceptor else transports.AsyncCloudRedisRestInterceptor(), - ) - client = CloudRedisAsyncClient(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.AsyncCloudRedisRestInterceptor, "post_get_instance_auth_string") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_get_instance_auth_string") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.GetInstanceAuthStringRequest.pb(cloud_redis.GetInstanceAuthStringRequest()) - 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 = cloud_redis.InstanceAuthString.to_json(cloud_redis.InstanceAuthString()) - req.return_value.read = mock.AsyncMock(return_value=return_value) - - request = cloud_redis.GetInstanceAuthStringRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.InstanceAuthString() - - await client.get_instance_auth_string(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -@pytest.mark.asyncio -async def test_create_instance_rest_asyncio_bad_request(request_type=cloud_redis.CreateInstanceRequest): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(AsyncAuthorizedSession, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.read = mock.AsyncMock(return_value=b'{}') - 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"} - await client.create_instance(request) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("request_type", [ - cloud_redis.CreateInstanceRequest, - dict, -]) -async def test_create_instance_rest_asyncio_call_success(request_type): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'labels': {}, 'location_id': 'location_id_value', 'alternative_location_id': 'alternative_location_id_value', 'redis_version': 'redis_version_value', 'reserved_ip_range': 'reserved_ip_range_value', 'secondary_ip_range': 'secondary_ip_range_value', 'host': 'host_value', 'port': 453, 'current_location_id': 'current_location_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'state': 1, 'status_message': 'status_message_value', 'redis_configs': {}, 'tier': 1, 'memory_size_gb': 1499, 'authorized_network': 'authorized_network_value', 'persistence_iam_identity': 'persistence_iam_identity_value', 'connect_mode': 1, 'auth_enabled': True, 'server_ca_certs': [{'serial_number': 'serial_number_value', 'cert': 'cert_value', 'create_time': {}, 'expire_time': {}, 'sha1_fingerprint': 'sha1_fingerprint_value'}], 'transit_encryption_mode': 1, 'maintenance_policy': {'create_time': {}, 'update_time': {}, 'description': 'description_value', 'weekly_maintenance_window': [{'day': 1, 'start_time': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'duration': {'seconds': 751, 'nanos': 543}}]}, 'maintenance_schedule': {'start_time': {}, 'end_time': {}, 'can_reschedule': True, 'schedule_deadline_time': {}}, 'replica_count': 1384, 'nodes': [{'id': 'id_value', 'zone': 'zone_value'}], 'read_endpoint': 'read_endpoint_value', 'read_endpoint_port': 1920, 'read_replicas_mode': 1, 'customer_managed_key': 'customer_managed_key_value', 'persistence_config': {'persistence_mode': 1, 'rdb_snapshot_period': 3, 'rdb_next_snapshot_time': {}, 'rdb_snapshot_start_time': {}}, 'suspension_reasons': [1], 'maintenance_version': 'maintenance_version_value', 'available_maintenance_versions': ['available_maintenance_versions_value1', 'available_maintenance_versions_value2']} - # 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 = cloud_redis.CreateInstanceRequest.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.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.create_instance(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_create_instance_rest_asyncio_interceptors(null_interceptor): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - transport = transports.AsyncCloudRedisRestTransport( - credentials=async_anonymous_credentials(), - interceptor=None if null_interceptor else transports.AsyncCloudRedisRestInterceptor(), - ) - client = CloudRedisAsyncClient(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.AsyncCloudRedisRestInterceptor, "post_create_instance") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_create_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.CreateInstanceRequest.pb(cloud_redis.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.read = mock.AsyncMock(return_value=return_value) - - request = cloud_redis.CreateInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - await client.create_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -@pytest.mark.asyncio -async def test_update_instance_rest_asyncio_bad_request(request_type=cloud_redis.UpdateInstanceRequest): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - # send a request that will satisfy transcoding - request_init = {'instance': {'name': 'projects/sample1/locations/sample2/instances/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(AsyncAuthorizedSession, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.read = mock.AsyncMock(return_value=b'{}') - 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"} - await client.update_instance(request) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("request_type", [ - cloud_redis.UpdateInstanceRequest, - dict, -]) -async def test_update_instance_rest_asyncio_call_success(request_type): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - - # send a request that will satisfy transcoding - request_init = {'instance': {'name': 'projects/sample1/locations/sample2/instances/sample3'}} - request_init["instance"] = {'name': 'projects/sample1/locations/sample2/instances/sample3', 'display_name': 'display_name_value', 'labels': {}, 'location_id': 'location_id_value', 'alternative_location_id': 'alternative_location_id_value', 'redis_version': 'redis_version_value', 'reserved_ip_range': 'reserved_ip_range_value', 'secondary_ip_range': 'secondary_ip_range_value', 'host': 'host_value', 'port': 453, 'current_location_id': 'current_location_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'state': 1, 'status_message': 'status_message_value', 'redis_configs': {}, 'tier': 1, 'memory_size_gb': 1499, 'authorized_network': 'authorized_network_value', 'persistence_iam_identity': 'persistence_iam_identity_value', 'connect_mode': 1, 'auth_enabled': True, 'server_ca_certs': [{'serial_number': 'serial_number_value', 'cert': 'cert_value', 'create_time': {}, 'expire_time': {}, 'sha1_fingerprint': 'sha1_fingerprint_value'}], 'transit_encryption_mode': 1, 'maintenance_policy': {'create_time': {}, 'update_time': {}, 'description': 'description_value', 'weekly_maintenance_window': [{'day': 1, 'start_time': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'duration': {'seconds': 751, 'nanos': 543}}]}, 'maintenance_schedule': {'start_time': {}, 'end_time': {}, 'can_reschedule': True, 'schedule_deadline_time': {}}, 'replica_count': 1384, 'nodes': [{'id': 'id_value', 'zone': 'zone_value'}], 'read_endpoint': 'read_endpoint_value', 'read_endpoint_port': 1920, 'read_replicas_mode': 1, 'customer_managed_key': 'customer_managed_key_value', 'persistence_config': {'persistence_mode': 1, 'rdb_snapshot_period': 3, 'rdb_next_snapshot_time': {}, 'rdb_snapshot_start_time': {}}, 'suspension_reasons': [1], 'maintenance_version': 'maintenance_version_value', 'available_maintenance_versions': ['available_maintenance_versions_value1', 'available_maintenance_versions_value2']} - # 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 = cloud_redis.UpdateInstanceRequest.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.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.update_instance(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_update_instance_rest_asyncio_interceptors(null_interceptor): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - transport = transports.AsyncCloudRedisRestTransport( - credentials=async_anonymous_credentials(), - interceptor=None if null_interceptor else transports.AsyncCloudRedisRestInterceptor(), - ) - client = CloudRedisAsyncClient(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.AsyncCloudRedisRestInterceptor, "post_update_instance") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_update_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.UpdateInstanceRequest.pb(cloud_redis.UpdateInstanceRequest()) - 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.read = mock.AsyncMock(return_value=return_value) - - request = cloud_redis.UpdateInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, +operations_v1.AbstractOperationsClient, + ) - await client.update_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + +def test_transport_kind_rest_asyncio(): + if not HAS_ASYNC_REST_EXTRA: + pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") + transport = CloudRedisAsyncClient.get_transport_class("rest_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "rest_asyncio" - pre.assert_called_once() - post.assert_called_once() @pytest.mark.asyncio -async def test_upgrade_instance_rest_asyncio_bad_request(request_type=cloud_redis.UpgradeInstanceRequest): +async def test_list_instances_rest_asyncio_bad_request(request_type=cloud_redis.ListInstancesRequest): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") client = CloudRedisAsyncClient( @@ -9849,7 +5149,7 @@ async def test_upgrade_instance_rest_asyncio_bad_request(request_type=cloud_redi transport="rest_asyncio" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request_init = {'parent': 'projects/sample1/locations/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9861,15 +5161,15 @@ async def test_upgrade_instance_rest_asyncio_bad_request(request_type=cloud_redi response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - await client.upgrade_instance(request) + await client.list_instances(request) @pytest.mark.asyncio @pytest.mark.parametrize("request_type", [ - cloud_redis.UpgradeInstanceRequest, + cloud_redis.ListInstancesRequest, dict, ]) -async def test_upgrade_instance_rest_asyncio_call_success(request_type): +async def test_list_instances_rest_asyncio_call_success(request_type): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") client = CloudRedisAsyncClient( @@ -9878,30 +5178,38 @@ async def test_upgrade_instance_rest_asyncio_call_success(request_type): ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request_init = {'parent': 'projects/sample1/locations/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 = cloud_redis.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = cloud_redis.ListInstancesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.upgrade_instance(request) + response = await client.list_instances(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.ListInstancesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] @pytest.mark.asyncio @pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_upgrade_instance_rest_asyncio_interceptors(null_interceptor): +async def test_list_instances_rest_asyncio_interceptors(null_interceptor): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") transport = transports.AsyncCloudRedisRestTransport( @@ -9912,12 +5220,11 @@ async def test_upgrade_instance_rest_asyncio_interceptors(null_interceptor): 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.AsyncCloudRedisRestInterceptor, "post_upgrade_instance") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_upgrade_instance") as pre: + mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "post_list_instances") as post, \ + mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_list_instances") as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_redis.UpgradeInstanceRequest.pb(cloud_redis.UpgradeInstanceRequest()) + pb_message = cloud_redis.ListInstancesRequest.pb(cloud_redis.ListInstancesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9928,24 +5235,24 @@ async def test_upgrade_instance_rest_asyncio_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()) + return_value = cloud_redis.ListInstancesResponse.to_json(cloud_redis.ListInstancesResponse()) req.return_value.read = mock.AsyncMock(return_value=return_value) - request = cloud_redis.UpgradeInstanceRequest() + request = cloud_redis.ListInstancesRequest() metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = cloud_redis.ListInstancesResponse() - await client.upgrade_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + await client.list_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() @pytest.mark.asyncio -async def test_import_instance_rest_asyncio_bad_request(request_type=cloud_redis.ImportInstanceRequest): +async def test_get_instance_rest_asyncio_bad_request(request_type=cloud_redis.GetInstanceRequest): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") client = CloudRedisAsyncClient( @@ -9965,15 +5272,15 @@ async def test_import_instance_rest_asyncio_bad_request(request_type=cloud_redis response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - await client.import_instance(request) + await client.get_instance(request) @pytest.mark.asyncio @pytest.mark.parametrize("request_type", [ - cloud_redis.ImportInstanceRequest, + cloud_redis.GetInstanceRequest, dict, ]) -async def test_import_instance_rest_asyncio_call_success(request_type): +async def test_get_instance_rest_asyncio_call_success(request_type): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") client = CloudRedisAsyncClient( @@ -9988,24 +5295,82 @@ async def test_import_instance_rest_asyncio_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 = operations_pb2.Operation(name='operations/spam') + return_value = cloud_redis.Instance( + name='name_value', + display_name='display_name_value', + location_id='location_id_value', + alternative_location_id='alternative_location_id_value', + redis_version='redis_version_value', + reserved_ip_range='reserved_ip_range_value', + secondary_ip_range='secondary_ip_range_value', + host='host_value', + port=453, + current_location_id='current_location_id_value', + state=cloud_redis.Instance.State.CREATING, + status_message='status_message_value', + tier=cloud_redis.Instance.Tier.BASIC, + memory_size_gb=1499, + authorized_network='authorized_network_value', + persistence_iam_identity='persistence_iam_identity_value', + connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, + auth_enabled=True, + transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, + replica_count=1384, + read_endpoint='read_endpoint_value', + read_endpoint_port=1920, + read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, + customer_managed_key='customer_managed_key_value', + suspension_reasons=[cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE], + maintenance_version='maintenance_version_value', + available_maintenance_versions=['available_maintenance_versions_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 = cloud_redis.Instance.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.import_instance(request) + response = await client.get_instance(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, cloud_redis.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.location_id == 'location_id_value' + assert response.alternative_location_id == 'alternative_location_id_value' + assert response.redis_version == 'redis_version_value' + assert response.reserved_ip_range == 'reserved_ip_range_value' + assert response.secondary_ip_range == 'secondary_ip_range_value' + assert response.host == 'host_value' + assert response.port == 453 + assert response.current_location_id == 'current_location_id_value' + assert response.state == cloud_redis.Instance.State.CREATING + assert response.status_message == 'status_message_value' + assert response.tier == cloud_redis.Instance.Tier.BASIC + assert response.memory_size_gb == 1499 + assert response.authorized_network == 'authorized_network_value' + assert response.persistence_iam_identity == 'persistence_iam_identity_value' + assert response.connect_mode == cloud_redis.Instance.ConnectMode.DIRECT_PEERING + assert response.auth_enabled is True + assert response.transit_encryption_mode == cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION + assert response.replica_count == 1384 + assert response.read_endpoint == 'read_endpoint_value' + assert response.read_endpoint_port == 1920 + assert response.read_replicas_mode == cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED + assert response.customer_managed_key == 'customer_managed_key_value' + assert response.suspension_reasons == [cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE] + assert response.maintenance_version == 'maintenance_version_value' + assert response.available_maintenance_versions == ['available_maintenance_versions_value'] @pytest.mark.asyncio @pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_import_instance_rest_asyncio_interceptors(null_interceptor): +async def test_get_instance_rest_asyncio_interceptors(null_interceptor): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") transport = transports.AsyncCloudRedisRestTransport( @@ -10016,12 +5381,11 @@ async def test_import_instance_rest_asyncio_interceptors(null_interceptor): 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.AsyncCloudRedisRestInterceptor, "post_import_instance") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_import_instance") as pre: + mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "post_get_instance") as post, \ + mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_get_instance") as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_redis.ImportInstanceRequest.pb(cloud_redis.ImportInstanceRequest()) + pb_message = cloud_redis.GetInstanceRequest.pb(cloud_redis.GetInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10032,24 +5396,24 @@ async def test_import_instance_rest_asyncio_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()) + return_value = cloud_redis.Instance.to_json(cloud_redis.Instance()) req.return_value.read = mock.AsyncMock(return_value=return_value) - request = cloud_redis.ImportInstanceRequest() + request = cloud_redis.GetInstanceRequest() metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = cloud_redis.Instance() - await client.import_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + await client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() @pytest.mark.asyncio -async def test_export_instance_rest_asyncio_bad_request(request_type=cloud_redis.ExportInstanceRequest): +async def test_create_instance_rest_asyncio_bad_request(request_type=cloud_redis.CreateInstanceRequest): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") client = CloudRedisAsyncClient( @@ -10057,7 +5421,7 @@ async def test_export_instance_rest_asyncio_bad_request(request_type=cloud_redis transport="rest_asyncio" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request_init = {'parent': 'projects/sample1/locations/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10069,15 +5433,15 @@ async def test_export_instance_rest_asyncio_bad_request(request_type=cloud_redis response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - await client.export_instance(request) + await client.create_instance(request) @pytest.mark.asyncio @pytest.mark.parametrize("request_type", [ - cloud_redis.ExportInstanceRequest, + cloud_redis.CreateInstanceRequest, dict, ]) -async def test_export_instance_rest_asyncio_call_success(request_type): +async def test_create_instance_rest_asyncio_call_success(request_type): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") client = CloudRedisAsyncClient( @@ -10086,111 +5450,71 @@ async def test_export_instance_rest_asyncio_call_success(request_type): ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/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 = 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.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.export_instance(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_export_instance_rest_asyncio_interceptors(null_interceptor): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - transport = transports.AsyncCloudRedisRestTransport( - credentials=async_anonymous_credentials(), - interceptor=None if null_interceptor else transports.AsyncCloudRedisRestInterceptor(), - ) - client = CloudRedisAsyncClient(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.AsyncCloudRedisRestInterceptor, "post_export_instance") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_export_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.ExportInstanceRequest.pb(cloud_redis.ExportInstanceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'labels': {}, 'location_id': 'location_id_value', 'alternative_location_id': 'alternative_location_id_value', 'redis_version': 'redis_version_value', 'reserved_ip_range': 'reserved_ip_range_value', 'secondary_ip_range': 'secondary_ip_range_value', 'host': 'host_value', 'port': 453, 'current_location_id': 'current_location_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'state': 1, 'status_message': 'status_message_value', 'redis_configs': {}, 'tier': 1, 'memory_size_gb': 1499, 'authorized_network': 'authorized_network_value', 'persistence_iam_identity': 'persistence_iam_identity_value', 'connect_mode': 1, 'auth_enabled': True, 'server_ca_certs': [{'serial_number': 'serial_number_value', 'cert': 'cert_value', 'create_time': {}, 'expire_time': {}, 'sha1_fingerprint': 'sha1_fingerprint_value'}], 'transit_encryption_mode': 1, 'maintenance_policy': {'create_time': {}, 'update_time': {}, 'description': 'description_value', 'weekly_maintenance_window': [{'day': 1, 'start_time': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'duration': {'seconds': 751, 'nanos': 543}}]}, 'maintenance_schedule': {'start_time': {}, 'end_time': {}, 'can_reschedule': True, 'schedule_deadline_time': {}}, 'replica_count': 1384, 'nodes': [{'id': 'id_value', 'zone': 'zone_value'}], 'read_endpoint': 'read_endpoint_value', 'read_endpoint_port': 1920, 'read_replicas_mode': 1, 'customer_managed_key': 'customer_managed_key_value', 'persistence_config': {'persistence_mode': 1, 'rdb_snapshot_period': 3, 'rdb_next_snapshot_time': {}, 'rdb_snapshot_start_time': {}}, 'suspension_reasons': [1], 'maintenance_version': 'maintenance_version_value', 'available_maintenance_versions': ['available_maintenance_versions_value1', 'available_maintenance_versions_value2']} + # 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 - 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.read = mock.AsyncMock(return_value=return_value) + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis.CreateInstanceRequest.meta.fields["instance"] - request = cloud_redis.ExportInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + 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 = [] - await client.export_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - pre.assert_called_once() - post.assert_called_once() + 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 -@pytest.mark.asyncio -async def test_failover_instance_rest_asyncio_bad_request(request_type=cloud_redis.FailoverInstanceRequest): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - request = request_type(**request_init) + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(AsyncAuthorizedSession, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.read = mock.AsyncMock(return_value=b'{}') - 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"} - await client.failover_instance(request) + 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 -@pytest.mark.asyncio -@pytest.mark.parametrize("request_type", [ - cloud_redis.FailoverInstanceRequest, - dict, -]) -async def test_failover_instance_rest_asyncio_call_success(request_type): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio" - ) + 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} + ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + # 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. @@ -10205,7 +5529,7 @@ async def test_failover_instance_rest_asyncio_call_success(request_type): response_value.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.failover_instance(request) + response = await client.create_instance(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @@ -10213,7 +5537,7 @@ async def test_failover_instance_rest_asyncio_call_success(request_type): @pytest.mark.asyncio @pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_failover_instance_rest_asyncio_interceptors(null_interceptor): +async def test_create_instance_rest_asyncio_interceptors(null_interceptor): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") transport = transports.AsyncCloudRedisRestTransport( @@ -10225,11 +5549,11 @@ async def test_failover_instance_rest_asyncio_interceptors(null_interceptor): 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.AsyncCloudRedisRestInterceptor, "post_failover_instance") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_failover_instance") as pre: + mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "post_create_instance") as post, \ + mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_create_instance") as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_redis.FailoverInstanceRequest.pb(cloud_redis.FailoverInstanceRequest()) + pb_message = cloud_redis.CreateInstanceRequest.pb(cloud_redis.CreateInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10243,7 +5567,7 @@ async def test_failover_instance_rest_asyncio_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.read = mock.AsyncMock(return_value=return_value) - request = cloud_redis.FailoverInstanceRequest() + request = cloud_redis.CreateInstanceRequest() metadata =[ ("key", "val"), ("cephalopod", "squid"), @@ -10251,13 +5575,13 @@ async def test_failover_instance_rest_asyncio_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - await client.failover_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + await client.create_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() @pytest.mark.asyncio -async def test_delete_instance_rest_asyncio_bad_request(request_type=cloud_redis.DeleteInstanceRequest): +async def test_update_instance_rest_asyncio_bad_request(request_type=cloud_redis.UpdateInstanceRequest): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") client = CloudRedisAsyncClient( @@ -10265,7 +5589,7 @@ async def test_delete_instance_rest_asyncio_bad_request(request_type=cloud_redis transport="rest_asyncio" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request_init = {'instance': {'name': 'projects/sample1/locations/sample2/instances/sample3'}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10277,15 +5601,15 @@ async def test_delete_instance_rest_asyncio_bad_request(request_type=cloud_redis response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - await client.delete_instance(request) + await client.update_instance(request) @pytest.mark.asyncio @pytest.mark.parametrize("request_type", [ - cloud_redis.DeleteInstanceRequest, + cloud_redis.UpdateInstanceRequest, dict, ]) -async def test_delete_instance_rest_asyncio_call_success(request_type): +async def test_update_instance_rest_asyncio_call_success(request_type): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") client = CloudRedisAsyncClient( @@ -10294,7 +5618,71 @@ async def test_delete_instance_rest_asyncio_call_success(request_type): ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request_init = {'instance': {'name': 'projects/sample1/locations/sample2/instances/sample3'}} + request_init["instance"] = {'name': 'projects/sample1/locations/sample2/instances/sample3', 'display_name': 'display_name_value', 'labels': {}, 'location_id': 'location_id_value', 'alternative_location_id': 'alternative_location_id_value', 'redis_version': 'redis_version_value', 'reserved_ip_range': 'reserved_ip_range_value', 'secondary_ip_range': 'secondary_ip_range_value', 'host': 'host_value', 'port': 453, 'current_location_id': 'current_location_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'state': 1, 'status_message': 'status_message_value', 'redis_configs': {}, 'tier': 1, 'memory_size_gb': 1499, 'authorized_network': 'authorized_network_value', 'persistence_iam_identity': 'persistence_iam_identity_value', 'connect_mode': 1, 'auth_enabled': True, 'server_ca_certs': [{'serial_number': 'serial_number_value', 'cert': 'cert_value', 'create_time': {}, 'expire_time': {}, 'sha1_fingerprint': 'sha1_fingerprint_value'}], 'transit_encryption_mode': 1, 'maintenance_policy': {'create_time': {}, 'update_time': {}, 'description': 'description_value', 'weekly_maintenance_window': [{'day': 1, 'start_time': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'duration': {'seconds': 751, 'nanos': 543}}]}, 'maintenance_schedule': {'start_time': {}, 'end_time': {}, 'can_reschedule': True, 'schedule_deadline_time': {}}, 'replica_count': 1384, 'nodes': [{'id': 'id_value', 'zone': 'zone_value'}], 'read_endpoint': 'read_endpoint_value', 'read_endpoint_port': 1920, 'read_replicas_mode': 1, 'customer_managed_key': 'customer_managed_key_value', 'persistence_config': {'persistence_mode': 1, 'rdb_snapshot_period': 3, 'rdb_next_snapshot_time': {}, 'rdb_snapshot_start_time': {}}, 'suspension_reasons': [1], 'maintenance_version': 'maintenance_version_value', 'available_maintenance_versions': ['available_maintenance_versions_value1', 'available_maintenance_versions_value2']} + # 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 = cloud_redis.UpdateInstanceRequest.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. @@ -10309,7 +5697,7 @@ async def test_delete_instance_rest_asyncio_call_success(request_type): response_value.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.delete_instance(request) + response = await client.update_instance(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @@ -10317,7 +5705,7 @@ async def test_delete_instance_rest_asyncio_call_success(request_type): @pytest.mark.asyncio @pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_delete_instance_rest_asyncio_interceptors(null_interceptor): +async def test_update_instance_rest_asyncio_interceptors(null_interceptor): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") transport = transports.AsyncCloudRedisRestTransport( @@ -10329,11 +5717,11 @@ async def test_delete_instance_rest_asyncio_interceptors(null_interceptor): 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.AsyncCloudRedisRestInterceptor, "post_delete_instance") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_delete_instance") as pre: + mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "post_update_instance") as post, \ + mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_update_instance") as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_redis.DeleteInstanceRequest.pb(cloud_redis.DeleteInstanceRequest()) + pb_message = cloud_redis.UpdateInstanceRequest.pb(cloud_redis.UpdateInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10347,7 +5735,7 @@ async def test_delete_instance_rest_asyncio_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.read = mock.AsyncMock(return_value=return_value) - request = cloud_redis.DeleteInstanceRequest() + request = cloud_redis.UpdateInstanceRequest() metadata =[ ("key", "val"), ("cephalopod", "squid"), @@ -10355,13 +5743,13 @@ async def test_delete_instance_rest_asyncio_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - await client.delete_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + await client.update_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() @pytest.mark.asyncio -async def test_reschedule_maintenance_rest_asyncio_bad_request(request_type=cloud_redis.RescheduleMaintenanceRequest): +async def test_delete_instance_rest_asyncio_bad_request(request_type=cloud_redis.DeleteInstanceRequest): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") client = CloudRedisAsyncClient( @@ -10381,15 +5769,15 @@ async def test_reschedule_maintenance_rest_asyncio_bad_request(request_type=clou response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - await client.reschedule_maintenance(request) + await client.delete_instance(request) @pytest.mark.asyncio @pytest.mark.parametrize("request_type", [ - cloud_redis.RescheduleMaintenanceRequest, + cloud_redis.DeleteInstanceRequest, dict, ]) -async def test_reschedule_maintenance_rest_asyncio_call_success(request_type): +async def test_delete_instance_rest_asyncio_call_success(request_type): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") client = CloudRedisAsyncClient( @@ -10413,7 +5801,7 @@ async def test_reschedule_maintenance_rest_asyncio_call_success(request_type): response_value.read = mock.AsyncMock(return_value=json_return_value.encode('UTF-8')) req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = await client.reschedule_maintenance(request) + response = await client.delete_instance(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @@ -10421,7 +5809,7 @@ async def test_reschedule_maintenance_rest_asyncio_call_success(request_type): @pytest.mark.asyncio @pytest.mark.parametrize("null_interceptor", [True, False]) -async def test_reschedule_maintenance_rest_asyncio_interceptors(null_interceptor): +async def test_delete_instance_rest_asyncio_interceptors(null_interceptor): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") transport = transports.AsyncCloudRedisRestTransport( @@ -10433,11 +5821,11 @@ async def test_reschedule_maintenance_rest_asyncio_interceptors(null_interceptor 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.AsyncCloudRedisRestInterceptor, "post_reschedule_maintenance") as post, \ - mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_reschedule_maintenance") as pre: + mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "post_delete_instance") as post, \ + mock.patch.object(transports.AsyncCloudRedisRestInterceptor, "pre_delete_instance") as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_redis.RescheduleMaintenanceRequest.pb(cloud_redis.RescheduleMaintenanceRequest()) + pb_message = cloud_redis.DeleteInstanceRequest.pb(cloud_redis.DeleteInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10451,7 +5839,7 @@ async def test_reschedule_maintenance_rest_asyncio_interceptors(null_interceptor return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.read = mock.AsyncMock(return_value=return_value) - request = cloud_redis.RescheduleMaintenanceRequest() + request = cloud_redis.DeleteInstanceRequest() metadata =[ ("key", "val"), ("cephalopod", "squid"), @@ -10459,7 +5847,7 @@ async def test_reschedule_maintenance_rest_asyncio_interceptors(null_interceptor pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - await client.reschedule_maintenance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + await client.delete_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() @@ -10916,31 +6304,6 @@ async def test_get_instance_empty_call_rest_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_get_instance_auth_string_empty_call_rest_asyncio(): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), - '__call__') as call: - await client.get_instance_auth_string(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.GetInstanceAuthStringRequest() - - 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 @@ -10991,106 +6354,6 @@ async def test_update_instance_empty_call_rest_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_upgrade_instance_empty_call_rest_asyncio(): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_instance), - '__call__') as call: - await client.upgrade_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.UpgradeInstanceRequest() - - 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_import_instance_empty_call_rest_asyncio(): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_instance), - '__call__') as call: - await client.import_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.ImportInstanceRequest() - - 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_export_instance_empty_call_rest_asyncio(): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_instance), - '__call__') as call: - await client.export_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.ExportInstanceRequest() - - 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_failover_instance_empty_call_rest_asyncio(): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), - '__call__') as call: - await client.failover_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.FailoverInstanceRequest() - - 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 @@ -11116,31 +6379,6 @@ async def test_delete_instance_empty_call_rest_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_reschedule_maintenance_empty_call_rest_asyncio(): - if not HAS_ASYNC_REST_EXTRA: - pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") - client = CloudRedisAsyncClient( - credentials=async_anonymous_credentials(), - transport="rest_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.reschedule_maintenance), - '__call__') as call: - await client.reschedule_maintenance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_redis.RescheduleMaintenanceRequest() - - assert args[0] == request_msg - - def test_cloud_redis_rest_asyncio_lro_client(): if not HAS_ASYNC_REST_EXTRA: pytest.skip("the library must be installed with the `async_rest` extra to test this feature.") @@ -11203,15 +6441,9 @@ def test_cloud_redis_base_transport(): methods = ( 'list_instances', 'get_instance', - 'get_instance_auth_string', 'create_instance', 'update_instance', - 'upgrade_instance', - 'import_instance', - 'export_instance', - 'failover_instance', 'delete_instance', - 'reschedule_maintenance', 'get_location', 'list_locations', 'get_operation', @@ -11468,33 +6700,15 @@ def test_cloud_redis_client_transport_session_collision(transport_name): session1 = client1.transport.get_instance._session session2 = client2.transport.get_instance._session assert session1 != session2 - session1 = client1.transport.get_instance_auth_string._session - session2 = client2.transport.get_instance_auth_string._session - assert session1 != session2 session1 = client1.transport.create_instance._session session2 = client2.transport.create_instance._session assert session1 != session2 session1 = client1.transport.update_instance._session session2 = client2.transport.update_instance._session assert session1 != session2 - session1 = client1.transport.upgrade_instance._session - session2 = client2.transport.upgrade_instance._session - assert session1 != session2 - session1 = client1.transport.import_instance._session - session2 = client2.transport.import_instance._session - assert session1 != session2 - session1 = client1.transport.export_instance._session - session2 = client2.transport.export_instance._session - assert session1 != session2 - session1 = client1.transport.failover_instance._session - session2 = client2.transport.failover_instance._session - assert session1 != session2 session1 = client1.transport.delete_instance._session session2 = client2.transport.delete_instance._session assert session1 != session2 - session1 = client1.transport.reschedule_maintenance._session - session2 = client2.transport.reschedule_maintenance._session - assert session1 != session2 def test_cloud_redis_grpc_transport_channel(): channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) diff --git a/tests/integration/redis_v1.yaml b/tests/integration/redis_v1.yaml index efb6675bbf..7e238bc928 100644 --- a/tests/integration/redis_v1.yaml +++ b/tests/integration/redis_v1.yaml @@ -78,5 +78,14 @@ publishing: library_settings: - version: 'google.cloud.redis.v1' python_settings: + common: + selective_gapic_generation: + methods: + - google.cloud.redis.v1.CloudRedis.CreateInstance + - google.cloud.redis.v1.CloudRedis.DeleteInstance + - google.cloud.redis.v1.CloudRedis.GetInstance + - google.cloud.redis.v1.CloudRedis.ListInstances + - google.cloud.redis.v1.CloudRedis.UpdateInstance experimental_features: rest_async_io_enabled: true + diff --git a/tests/unit/schema/test_api.py b/tests/unit/schema/test_api.py index a11a3b747c..15968c0064 100644 --- a/tests/unit/schema/test_api.py +++ b/tests/unit/schema/test_api.py @@ -14,7 +14,7 @@ import collections import re -from typing import Sequence +from typing import Any, Dict, Sequence from unittest import mock import yaml @@ -2726,6 +2726,47 @@ def test_read_python_settings_from_service_yaml(): } +def test_read_selective_gapic_methods_from_service_yaml(): + service_yaml_config = { + "apis": [ + {"name": "google.example.v1beta1.ServiceOne.Example1"}, + ], + "publishing": { + "library_settings": [ + { + "version": "google.example.v1beta1", + "python_settings": { + "experimental_features": {"rest_async_io_enabled": True}, + "common": { + "selective_gapic_generation": { + "methods": ["google.example.v1beta1.ServiceOne.Example1"] + } + } + }, + } + ] + }, + } + cli_options = Options(service_yaml_config=service_yaml_config) + fd = get_file_descriptor_proto_for_tests(fields=[]) + api_schema = api.API.build(fd, "google.example.v1beta1", opts=cli_options) + assert api_schema.all_library_settings == { + "google.example.v1beta1": client_pb2.ClientLibrarySettings( + version="google.example.v1beta1", + python_settings=client_pb2.PythonSettings( + experimental_features=client_pb2.PythonSettings.ExperimentalFeatures( + rest_async_io_enabled=True + ), + common=client_pb2.CommonLanguageSettings( + selective_gapic_generation=client_pb2.SelectiveGapicGeneration( + methods=["google.example.v1beta1.ServiceOne.Example1"] + ) + ) + ), + ) + } + + def test_read_empty_python_settings_from_service_yaml(): service_yaml_config = { "apis": [ @@ -2743,6 +2784,8 @@ def test_read_empty_python_settings_from_service_yaml(): == False assert api_schema.all_library_settings[api_schema.naming.proto_package].python_settings \ == client_pb2.PythonSettings() + assert api_schema.all_library_settings["google.example.v1beta1"].python_settings.common \ + == client_pb2.CommonLanguageSettings() def test_python_settings_selective_gapic_nonexistent_method_raises_error():