diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/__init__.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/__init__.py index 3ed60ba8d354..11d67c2288db 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/__init__.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/__init__.py @@ -25,13 +25,16 @@ AccessConfig, AttachedDisk, CreateNodeRequest, + CreateQueuedResourceRequest, DeleteNodeRequest, + DeleteQueuedResourceRequest, GenerateServiceIdentityRequest, GenerateServiceIdentityResponse, GetAcceleratorTypeRequest, GetGuestAttributesRequest, GetGuestAttributesResponse, GetNodeRequest, + GetQueuedResourceRequest, GetRuntimeVersionRequest, GuestAttributes, GuestAttributesEntry, @@ -40,12 +43,17 @@ ListAcceleratorTypesResponse, ListNodesRequest, ListNodesResponse, + ListQueuedResourcesRequest, + ListQueuedResourcesResponse, ListRuntimeVersionsRequest, ListRuntimeVersionsResponse, NetworkConfig, NetworkEndpoint, Node, OperationMetadata, + QueuedResource, + QueuedResourceState, + ResetQueuedResourceRequest, RuntimeVersion, SchedulingConfig, ServiceAccount, @@ -64,13 +72,16 @@ "AccessConfig", "AttachedDisk", "CreateNodeRequest", + "CreateQueuedResourceRequest", "DeleteNodeRequest", + "DeleteQueuedResourceRequest", "GenerateServiceIdentityRequest", "GenerateServiceIdentityResponse", "GetAcceleratorTypeRequest", "GetGuestAttributesRequest", "GetGuestAttributesResponse", "GetNodeRequest", + "GetQueuedResourceRequest", "GetRuntimeVersionRequest", "GuestAttributes", "GuestAttributesEntry", @@ -79,12 +90,17 @@ "ListAcceleratorTypesResponse", "ListNodesRequest", "ListNodesResponse", + "ListQueuedResourcesRequest", + "ListQueuedResourcesResponse", "ListRuntimeVersionsRequest", "ListRuntimeVersionsResponse", "NetworkConfig", "NetworkEndpoint", "Node", "OperationMetadata", + "QueuedResource", + "QueuedResourceState", + "ResetQueuedResourceRequest", "RuntimeVersion", "SchedulingConfig", "ServiceAccount", diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/gapic_metadata.json b/packages/google-cloud-tpu/google/cloud/tpu_v2/gapic_metadata.json index fd9a15fa8ca8..08f907efeed1 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/gapic_metadata.json +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/gapic_metadata.json @@ -15,11 +15,21 @@ "create_node" ] }, + "CreateQueuedResource": { + "methods": [ + "create_queued_resource" + ] + }, "DeleteNode": { "methods": [ "delete_node" ] }, + "DeleteQueuedResource": { + "methods": [ + "delete_queued_resource" + ] + }, "GenerateServiceIdentity": { "methods": [ "generate_service_identity" @@ -40,6 +50,11 @@ "get_node" ] }, + "GetQueuedResource": { + "methods": [ + "get_queued_resource" + ] + }, "GetRuntimeVersion": { "methods": [ "get_runtime_version" @@ -55,11 +70,21 @@ "list_nodes" ] }, + "ListQueuedResources": { + "methods": [ + "list_queued_resources" + ] + }, "ListRuntimeVersions": { "methods": [ "list_runtime_versions" ] }, + "ResetQueuedResource": { + "methods": [ + "reset_queued_resource" + ] + }, "StartNode": { "methods": [ "start_node" @@ -85,11 +110,21 @@ "create_node" ] }, + "CreateQueuedResource": { + "methods": [ + "create_queued_resource" + ] + }, "DeleteNode": { "methods": [ "delete_node" ] }, + "DeleteQueuedResource": { + "methods": [ + "delete_queued_resource" + ] + }, "GenerateServiceIdentity": { "methods": [ "generate_service_identity" @@ -110,6 +145,11 @@ "get_node" ] }, + "GetQueuedResource": { + "methods": [ + "get_queued_resource" + ] + }, "GetRuntimeVersion": { "methods": [ "get_runtime_version" @@ -125,11 +165,21 @@ "list_nodes" ] }, + "ListQueuedResources": { + "methods": [ + "list_queued_resources" + ] + }, "ListRuntimeVersions": { "methods": [ "list_runtime_versions" ] }, + "ResetQueuedResource": { + "methods": [ + "reset_queued_resource" + ] + }, "StartNode": { "methods": [ "start_node" @@ -155,11 +205,21 @@ "create_node" ] }, + "CreateQueuedResource": { + "methods": [ + "create_queued_resource" + ] + }, "DeleteNode": { "methods": [ "delete_node" ] }, + "DeleteQueuedResource": { + "methods": [ + "delete_queued_resource" + ] + }, "GenerateServiceIdentity": { "methods": [ "generate_service_identity" @@ -180,6 +240,11 @@ "get_node" ] }, + "GetQueuedResource": { + "methods": [ + "get_queued_resource" + ] + }, "GetRuntimeVersion": { "methods": [ "get_runtime_version" @@ -195,11 +260,21 @@ "list_nodes" ] }, + "ListQueuedResources": { + "methods": [ + "list_queued_resources" + ] + }, "ListRuntimeVersions": { "methods": [ "list_runtime_versions" ] }, + "ResetQueuedResource": { + "methods": [ + "reset_queued_resource" + ] + }, "StartNode": { "methods": [ "start_node" diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/async_client.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/async_client.py index fc86217c4265..832090ea011d 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/async_client.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/async_client.py @@ -87,6 +87,8 @@ class TpuAsyncClient: parse_accelerator_type_path = staticmethod(TpuClient.parse_accelerator_type_path) node_path = staticmethod(TpuClient.node_path) parse_node_path = staticmethod(TpuClient.parse_node_path) + queued_resource_path = staticmethod(TpuClient.queued_resource_path) + parse_queued_resource_path = staticmethod(TpuClient.parse_queued_resource_path) runtime_version_path = staticmethod(TpuClient.runtime_version_path) parse_runtime_version_path = staticmethod(TpuClient.parse_runtime_version_path) common_billing_account_path = staticmethod(TpuClient.common_billing_account_path) @@ -1120,6 +1122,625 @@ async def sample_update_node(): # Done; return the response. return response + async def list_queued_resources( + self, + request: Optional[Union[cloud_tpu.ListQueuedResourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListQueuedResourcesAsyncPager: + r"""Lists queued resources. + + .. 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 tpu_v2 + + async def sample_list_queued_resources(): + # Create a client + client = tpu_v2.TpuAsyncClient() + + # Initialize request argument(s) + request = tpu_v2.ListQueuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_queued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.tpu_v2.types.ListQueuedResourcesRequest, dict]]): + The request object. Request for + [ListQueuedResources][google.cloud.tpu.v2.Tpu.ListQueuedResources]. + parent (:class:`str`): + Required. The parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.tpu_v2.services.tpu.pagers.ListQueuedResourcesAsyncPager: + Response for + [ListQueuedResources][google.cloud.tpu.v2.Tpu.ListQueuedResources]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - 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_tpu.ListQueuedResourcesRequest): + request = cloud_tpu.ListQueuedResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_queued_resources + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListQueuedResourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_queued_resource( + self, + request: Optional[Union[cloud_tpu.GetQueuedResourceRequest, 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_tpu.QueuedResource: + r"""Gets details of a queued resource. + + .. 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 tpu_v2 + + async def sample_get_queued_resource(): + # Create a client + client = tpu_v2.TpuAsyncClient() + + # Initialize request argument(s) + request = tpu_v2.GetQueuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_queued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.tpu_v2.types.GetQueuedResourceRequest, dict]]): + The request object. Request for + [GetQueuedResource][google.cloud.tpu.v2.Tpu.GetQueuedResource] + name (:class:`str`): + Required. The resource name. + 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.tpu_v2.types.QueuedResource: + A QueuedResource represents a request + for resources that will be placed in a + queue and fulfilled when the necessary + resources are available. + + """ + # 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_tpu.GetQueuedResourceRequest): + request = cloud_tpu.GetQueuedResourceRequest(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_queued_resource + ] + + # 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_queued_resource( + self, + request: Optional[Union[cloud_tpu.CreateQueuedResourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + queued_resource: Optional[cloud_tpu.QueuedResource] = None, + queued_resource_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a QueuedResource TPU 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 tpu_v2 + + async def sample_create_queued_resource(): + # Create a client + client = tpu_v2.TpuAsyncClient() + + # Initialize request argument(s) + request = tpu_v2.CreateQueuedResourceRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.tpu_v2.types.CreateQueuedResourceRequest, dict]]): + The request object. Request for + [CreateQueuedResource][google.cloud.tpu.v2.Tpu.CreateQueuedResource]. + parent (:class:`str`): + Required. The parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + queued_resource (:class:`google.cloud.tpu_v2.types.QueuedResource`): + Required. The queued resource. + This corresponds to the ``queued_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + queued_resource_id (:class:`str`): + Optional. The unqualified resource name. Should follow + the ``^[A-Za-z0-9_.~+%-]+$`` regex format. + + This corresponds to the ``queued_resource_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.tpu_v2.types.QueuedResource` A QueuedResource represents a request for resources that will be placed + in a queue and fulfilled when the necessary resources + are available. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, queued_resource, queued_resource_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - 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_tpu.CreateQueuedResourceRequest): + request = cloud_tpu.CreateQueuedResourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if queued_resource is not None: + request.queued_resource = queued_resource + if queued_resource_id is not None: + request.queued_resource_id = queued_resource_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_queued_resource + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + cloud_tpu.QueuedResource, + metadata_type=cloud_tpu.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_queued_resource( + self, + request: Optional[Union[cloud_tpu.DeleteQueuedResourceRequest, 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 QueuedResource TPU 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 tpu_v2 + + async def sample_delete_queued_resource(): + # Create a client + client = tpu_v2.TpuAsyncClient() + + # Initialize request argument(s) + request = tpu_v2.DeleteQueuedResourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.tpu_v2.types.DeleteQueuedResourceRequest, dict]]): + The request object. Request for + [DeleteQueuedResource][google.cloud.tpu.v2.Tpu.DeleteQueuedResource]. + name (:class:`str`): + Required. The resource name. + 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_tpu.DeleteQueuedResourceRequest): + request = cloud_tpu.DeleteQueuedResourceRequest(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_queued_resource + ] + + # 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, + empty_pb2.Empty, + metadata_type=cloud_tpu.OperationMetadata, + ) + + # Done; return the response. + return response + + async def reset_queued_resource( + self, + request: Optional[Union[cloud_tpu.ResetQueuedResourceRequest, 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"""Resets a QueuedResource TPU 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 tpu_v2 + + async def sample_reset_queued_resource(): + # Create a client + client = tpu_v2.TpuAsyncClient() + + # Initialize request argument(s) + request = tpu_v2.ResetQueuedResourceRequest( + name="name_value", + ) + + # Make the request + operation = client.reset_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.tpu_v2.types.ResetQueuedResourceRequest, dict]]): + The request object. Request for + [ResetQueuedResource][google.cloud.tpu.v2.Tpu.ResetQueuedResource]. + name (:class:`str`): + Required. The name of the queued + resource. + + 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.cloud.tpu_v2.types.QueuedResource` A QueuedResource represents a request for resources that will be placed + in a queue and fulfilled when the necessary resources + are available. + + """ + # 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_tpu.ResetQueuedResourceRequest): + request = cloud_tpu.ResetQueuedResourceRequest(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.reset_queued_resource + ] + + # 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_tpu.QueuedResource, + metadata_type=cloud_tpu.OperationMetadata, + ) + + # Done; return the response. + return response + async def generate_service_identity( self, request: Optional[Union[cloud_tpu.GenerateServiceIdentityRequest, dict]] = None, diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/client.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/client.py index 67b951a51ffa..74c58c498793 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/client.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/client.py @@ -246,6 +246,28 @@ def parse_node_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def queued_resource_path( + project: str, + location: str, + queued_resource: str, + ) -> str: + """Returns a fully-qualified queued_resource string.""" + return "projects/{project}/locations/{location}/queuedResources/{queued_resource}".format( + project=project, + location=location, + queued_resource=queued_resource, + ) + + @staticmethod + def parse_queued_resource_path(path: str) -> Dict[str, str]: + """Parses a queued_resource path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/queuedResources/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def runtime_version_path( project: str, @@ -1540,6 +1562,610 @@ def sample_update_node(): # Done; return the response. return response + def list_queued_resources( + self, + request: Optional[Union[cloud_tpu.ListQueuedResourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListQueuedResourcesPager: + r"""Lists queued resources. + + .. 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 tpu_v2 + + def sample_list_queued_resources(): + # Create a client + client = tpu_v2.TpuClient() + + # Initialize request argument(s) + request = tpu_v2.ListQueuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_queued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.tpu_v2.types.ListQueuedResourcesRequest, dict]): + The request object. Request for + [ListQueuedResources][google.cloud.tpu.v2.Tpu.ListQueuedResources]. + parent (str): + Required. The parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.tpu_v2.services.tpu.pagers.ListQueuedResourcesPager: + Response for + [ListQueuedResources][google.cloud.tpu.v2.Tpu.ListQueuedResources]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - 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_tpu.ListQueuedResourcesRequest): + request = cloud_tpu.ListQueuedResourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_queued_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListQueuedResourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_queued_resource( + self, + request: Optional[Union[cloud_tpu.GetQueuedResourceRequest, 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_tpu.QueuedResource: + r"""Gets details of a queued resource. + + .. 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 tpu_v2 + + def sample_get_queued_resource(): + # Create a client + client = tpu_v2.TpuClient() + + # Initialize request argument(s) + request = tpu_v2.GetQueuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_queued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.tpu_v2.types.GetQueuedResourceRequest, dict]): + The request object. Request for + [GetQueuedResource][google.cloud.tpu.v2.Tpu.GetQueuedResource] + name (str): + Required. The resource name. + 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.tpu_v2.types.QueuedResource: + A QueuedResource represents a request + for resources that will be placed in a + queue and fulfilled when the necessary + resources are available. + + """ + # 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_tpu.GetQueuedResourceRequest): + request = cloud_tpu.GetQueuedResourceRequest(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_queued_resource] + + # 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_queued_resource( + self, + request: Optional[Union[cloud_tpu.CreateQueuedResourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + queued_resource: Optional[cloud_tpu.QueuedResource] = None, + queued_resource_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a QueuedResource TPU 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 tpu_v2 + + def sample_create_queued_resource(): + # Create a client + client = tpu_v2.TpuClient() + + # Initialize request argument(s) + request = tpu_v2.CreateQueuedResourceRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.tpu_v2.types.CreateQueuedResourceRequest, dict]): + The request object. Request for + [CreateQueuedResource][google.cloud.tpu.v2.Tpu.CreateQueuedResource]. + parent (str): + Required. The parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + queued_resource (google.cloud.tpu_v2.types.QueuedResource): + Required. The queued resource. + This corresponds to the ``queued_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + queued_resource_id (str): + Optional. The unqualified resource name. Should follow + the ``^[A-Za-z0-9_.~+%-]+$`` regex format. + + This corresponds to the ``queued_resource_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.tpu_v2.types.QueuedResource` A QueuedResource represents a request for resources that will be placed + in a queue and fulfilled when the necessary resources + are available. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, queued_resource, queued_resource_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - 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_tpu.CreateQueuedResourceRequest): + request = cloud_tpu.CreateQueuedResourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if queued_resource is not None: + request.queued_resource = queued_resource + if queued_resource_id is not None: + request.queued_resource_id = queued_resource_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_queued_resource] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_tpu.QueuedResource, + metadata_type=cloud_tpu.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_queued_resource( + self, + request: Optional[Union[cloud_tpu.DeleteQueuedResourceRequest, 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 QueuedResource TPU 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 tpu_v2 + + def sample_delete_queued_resource(): + # Create a client + client = tpu_v2.TpuClient() + + # Initialize request argument(s) + request = tpu_v2.DeleteQueuedResourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.tpu_v2.types.DeleteQueuedResourceRequest, dict]): + The request object. Request for + [DeleteQueuedResource][google.cloud.tpu.v2.Tpu.DeleteQueuedResource]. + name (str): + Required. The resource name. + 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_tpu.DeleteQueuedResourceRequest): + request = cloud_tpu.DeleteQueuedResourceRequest(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_queued_resource] + + # 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, + empty_pb2.Empty, + metadata_type=cloud_tpu.OperationMetadata, + ) + + # Done; return the response. + return response + + def reset_queued_resource( + self, + request: Optional[Union[cloud_tpu.ResetQueuedResourceRequest, 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"""Resets a QueuedResource TPU 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 tpu_v2 + + def sample_reset_queued_resource(): + # Create a client + client = tpu_v2.TpuClient() + + # Initialize request argument(s) + request = tpu_v2.ResetQueuedResourceRequest( + name="name_value", + ) + + # Make the request + operation = client.reset_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.tpu_v2.types.ResetQueuedResourceRequest, dict]): + The request object. Request for + [ResetQueuedResource][google.cloud.tpu.v2.Tpu.ResetQueuedResource]. + name (str): + Required. The name of the queued + resource. + + 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.cloud.tpu_v2.types.QueuedResource` A QueuedResource represents a request for resources that will be placed + in a queue and fulfilled when the necessary resources + are available. + + """ + # 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_tpu.ResetQueuedResourceRequest): + request = cloud_tpu.ResetQueuedResourceRequest(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.reset_queued_resource] + + # 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_tpu.QueuedResource, + metadata_type=cloud_tpu.OperationMetadata, + ) + + # Done; return the response. + return response + def generate_service_identity( self, request: Optional[Union[cloud_tpu.GenerateServiceIdentityRequest, dict]] = None, diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/pagers.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/pagers.py index bb2fa56c220a..94f4abb495ea 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/pagers.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/pagers.py @@ -197,6 +197,162 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListQueuedResourcesPager: + """A pager for iterating through ``list_queued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.tpu_v2.types.ListQueuedResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``queued_resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListQueuedResources`` requests and continue to iterate + through the ``queued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.tpu_v2.types.ListQueuedResourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., cloud_tpu.ListQueuedResourcesResponse], + request: cloud_tpu.ListQueuedResourcesRequest, + response: cloud_tpu.ListQueuedResourcesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.tpu_v2.types.ListQueuedResourcesRequest): + The initial request object. + response (google.cloud.tpu_v2.types.ListQueuedResourcesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = cloud_tpu.ListQueuedResourcesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[cloud_tpu.ListQueuedResourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[cloud_tpu.QueuedResource]: + for page in self.pages: + yield from page.queued_resources + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListQueuedResourcesAsyncPager: + """A pager for iterating through ``list_queued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.tpu_v2.types.ListQueuedResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``queued_resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListQueuedResources`` requests and continue to iterate + through the ``queued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.tpu_v2.types.ListQueuedResourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[cloud_tpu.ListQueuedResourcesResponse]], + request: cloud_tpu.ListQueuedResourcesRequest, + response: cloud_tpu.ListQueuedResourcesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.tpu_v2.types.ListQueuedResourcesRequest): + The initial request object. + response (google.cloud.tpu_v2.types.ListQueuedResourcesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = cloud_tpu.ListQueuedResourcesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[cloud_tpu.ListQueuedResourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[cloud_tpu.QueuedResource]: + async def async_generator(): + async for page in self.pages: + for response in page.queued_resources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListAcceleratorTypesPager: """A pager for iterating through ``list_accelerator_types`` requests. diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/base.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/base.py index e56986de4e77..b49ee9f44951 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/base.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/base.py @@ -165,6 +165,31 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.list_queued_resources: gapic_v1.method.wrap_method( + self.list_queued_resources, + default_timeout=None, + client_info=client_info, + ), + self.get_queued_resource: gapic_v1.method.wrap_method( + self.get_queued_resource, + default_timeout=None, + client_info=client_info, + ), + self.create_queued_resource: gapic_v1.method.wrap_method( + self.create_queued_resource, + default_timeout=None, + client_info=client_info, + ), + self.delete_queued_resource: gapic_v1.method.wrap_method( + self.delete_queued_resource, + default_timeout=None, + client_info=client_info, + ), + self.reset_queued_resource: gapic_v1.method.wrap_method( + self.reset_queued_resource, + default_timeout=None, + client_info=client_info, + ), self.generate_service_identity: gapic_v1.method.wrap_method( self.generate_service_identity, default_timeout=None, @@ -303,6 +328,54 @@ def update_node( ]: raise NotImplementedError() + @property + def list_queued_resources( + self, + ) -> Callable[ + [cloud_tpu.ListQueuedResourcesRequest], + Union[ + cloud_tpu.ListQueuedResourcesResponse, + Awaitable[cloud_tpu.ListQueuedResourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_queued_resource( + self, + ) -> Callable[ + [cloud_tpu.GetQueuedResourceRequest], + Union[cloud_tpu.QueuedResource, Awaitable[cloud_tpu.QueuedResource]], + ]: + raise NotImplementedError() + + @property + def create_queued_resource( + self, + ) -> Callable[ + [cloud_tpu.CreateQueuedResourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_queued_resource( + self, + ) -> Callable[ + [cloud_tpu.DeleteQueuedResourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def reset_queued_resource( + self, + ) -> Callable[ + [cloud_tpu.ResetQueuedResourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def generate_service_identity( self, diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/grpc.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/grpc.py index 6c57707898ab..6fd6753f466b 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/grpc.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/grpc.py @@ -522,6 +522,138 @@ def update_node( ) return self._stubs["update_node"] + @property + def list_queued_resources( + self, + ) -> Callable[ + [cloud_tpu.ListQueuedResourcesRequest], cloud_tpu.ListQueuedResourcesResponse + ]: + r"""Return a callable for the list queued resources method over gRPC. + + Lists queued resources. + + Returns: + Callable[[~.ListQueuedResourcesRequest], + ~.ListQueuedResourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_queued_resources" not in self._stubs: + self._stubs["list_queued_resources"] = self._logged_channel.unary_unary( + "/google.cloud.tpu.v2.Tpu/ListQueuedResources", + request_serializer=cloud_tpu.ListQueuedResourcesRequest.serialize, + response_deserializer=cloud_tpu.ListQueuedResourcesResponse.deserialize, + ) + return self._stubs["list_queued_resources"] + + @property + def get_queued_resource( + self, + ) -> Callable[[cloud_tpu.GetQueuedResourceRequest], cloud_tpu.QueuedResource]: + r"""Return a callable for the get queued resource method over gRPC. + + Gets details of a queued resource. + + Returns: + Callable[[~.GetQueuedResourceRequest], + ~.QueuedResource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_queued_resource" not in self._stubs: + self._stubs["get_queued_resource"] = self._logged_channel.unary_unary( + "/google.cloud.tpu.v2.Tpu/GetQueuedResource", + request_serializer=cloud_tpu.GetQueuedResourceRequest.serialize, + response_deserializer=cloud_tpu.QueuedResource.deserialize, + ) + return self._stubs["get_queued_resource"] + + @property + def create_queued_resource( + self, + ) -> Callable[[cloud_tpu.CreateQueuedResourceRequest], operations_pb2.Operation]: + r"""Return a callable for the create queued resource method over gRPC. + + Creates a QueuedResource TPU instance. + + Returns: + Callable[[~.CreateQueuedResourceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_queued_resource" not in self._stubs: + self._stubs["create_queued_resource"] = self._logged_channel.unary_unary( + "/google.cloud.tpu.v2.Tpu/CreateQueuedResource", + request_serializer=cloud_tpu.CreateQueuedResourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_queued_resource"] + + @property + def delete_queued_resource( + self, + ) -> Callable[[cloud_tpu.DeleteQueuedResourceRequest], operations_pb2.Operation]: + r"""Return a callable for the delete queued resource method over gRPC. + + Deletes a QueuedResource TPU instance. + + Returns: + Callable[[~.DeleteQueuedResourceRequest], + ~.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 "delete_queued_resource" not in self._stubs: + self._stubs["delete_queued_resource"] = self._logged_channel.unary_unary( + "/google.cloud.tpu.v2.Tpu/DeleteQueuedResource", + request_serializer=cloud_tpu.DeleteQueuedResourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_queued_resource"] + + @property + def reset_queued_resource( + self, + ) -> Callable[[cloud_tpu.ResetQueuedResourceRequest], operations_pb2.Operation]: + r"""Return a callable for the reset queued resource method over gRPC. + + Resets a QueuedResource TPU instance + + Returns: + Callable[[~.ResetQueuedResourceRequest], + ~.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 "reset_queued_resource" not in self._stubs: + self._stubs["reset_queued_resource"] = self._logged_channel.unary_unary( + "/google.cloud.tpu.v2.Tpu/ResetQueuedResource", + request_serializer=cloud_tpu.ResetQueuedResourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["reset_queued_resource"] + @property def generate_service_identity( self, diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/grpc_asyncio.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/grpc_asyncio.py index ae51d9091420..a0d244f03bca 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/grpc_asyncio.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/grpc_asyncio.py @@ -531,6 +531,147 @@ def update_node( ) return self._stubs["update_node"] + @property + def list_queued_resources( + self, + ) -> Callable[ + [cloud_tpu.ListQueuedResourcesRequest], + Awaitable[cloud_tpu.ListQueuedResourcesResponse], + ]: + r"""Return a callable for the list queued resources method over gRPC. + + Lists queued resources. + + Returns: + Callable[[~.ListQueuedResourcesRequest], + Awaitable[~.ListQueuedResourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_queued_resources" not in self._stubs: + self._stubs["list_queued_resources"] = self._logged_channel.unary_unary( + "/google.cloud.tpu.v2.Tpu/ListQueuedResources", + request_serializer=cloud_tpu.ListQueuedResourcesRequest.serialize, + response_deserializer=cloud_tpu.ListQueuedResourcesResponse.deserialize, + ) + return self._stubs["list_queued_resources"] + + @property + def get_queued_resource( + self, + ) -> Callable[ + [cloud_tpu.GetQueuedResourceRequest], Awaitable[cloud_tpu.QueuedResource] + ]: + r"""Return a callable for the get queued resource method over gRPC. + + Gets details of a queued resource. + + Returns: + Callable[[~.GetQueuedResourceRequest], + Awaitable[~.QueuedResource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_queued_resource" not in self._stubs: + self._stubs["get_queued_resource"] = self._logged_channel.unary_unary( + "/google.cloud.tpu.v2.Tpu/GetQueuedResource", + request_serializer=cloud_tpu.GetQueuedResourceRequest.serialize, + response_deserializer=cloud_tpu.QueuedResource.deserialize, + ) + return self._stubs["get_queued_resource"] + + @property + def create_queued_resource( + self, + ) -> Callable[ + [cloud_tpu.CreateQueuedResourceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create queued resource method over gRPC. + + Creates a QueuedResource TPU instance. + + Returns: + Callable[[~.CreateQueuedResourceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_queued_resource" not in self._stubs: + self._stubs["create_queued_resource"] = self._logged_channel.unary_unary( + "/google.cloud.tpu.v2.Tpu/CreateQueuedResource", + request_serializer=cloud_tpu.CreateQueuedResourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_queued_resource"] + + @property + def delete_queued_resource( + self, + ) -> Callable[ + [cloud_tpu.DeleteQueuedResourceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete queued resource method over gRPC. + + Deletes a QueuedResource TPU instance. + + Returns: + Callable[[~.DeleteQueuedResourceRequest], + 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 "delete_queued_resource" not in self._stubs: + self._stubs["delete_queued_resource"] = self._logged_channel.unary_unary( + "/google.cloud.tpu.v2.Tpu/DeleteQueuedResource", + request_serializer=cloud_tpu.DeleteQueuedResourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_queued_resource"] + + @property + def reset_queued_resource( + self, + ) -> Callable[ + [cloud_tpu.ResetQueuedResourceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the reset queued resource method over gRPC. + + Resets a QueuedResource TPU instance + + Returns: + Callable[[~.ResetQueuedResourceRequest], + 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 "reset_queued_resource" not in self._stubs: + self._stubs["reset_queued_resource"] = self._logged_channel.unary_unary( + "/google.cloud.tpu.v2.Tpu/ResetQueuedResource", + request_serializer=cloud_tpu.ResetQueuedResourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["reset_queued_resource"] + @property def generate_service_identity( self, @@ -742,6 +883,31 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.list_queued_resources: self._wrap_method( + self.list_queued_resources, + default_timeout=None, + client_info=client_info, + ), + self.get_queued_resource: self._wrap_method( + self.get_queued_resource, + default_timeout=None, + client_info=client_info, + ), + self.create_queued_resource: self._wrap_method( + self.create_queued_resource, + default_timeout=None, + client_info=client_info, + ), + self.delete_queued_resource: self._wrap_method( + self.delete_queued_resource, + default_timeout=None, + client_info=client_info, + ), + self.reset_queued_resource: self._wrap_method( + self.reset_queued_resource, + default_timeout=None, + client_info=client_info, + ), self.generate_service_identity: self._wrap_method( self.generate_service_identity, default_timeout=None, diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/rest.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/rest.py index d503b356ff39..36e14909f812 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/rest.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/rest.py @@ -78,6 +78,14 @@ def post_create_node(self, response): logging.log(f"Received response: {response}") return response + def pre_create_queued_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_queued_resource(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_node(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -86,6 +94,14 @@ def post_delete_node(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_queued_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_queued_resource(self, response): + logging.log(f"Received response: {response}") + return response + def pre_generate_service_identity(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -118,6 +134,14 @@ def post_get_node(self, response): logging.log(f"Received response: {response}") return response + def pre_get_queued_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_queued_resource(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_runtime_version(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -142,6 +166,14 @@ def post_list_nodes(self, response): logging.log(f"Received response: {response}") return response + def pre_list_queued_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_queued_resources(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_runtime_versions(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -150,6 +182,14 @@ def post_list_runtime_versions(self, response): logging.log(f"Received response: {response}") return response + def pre_reset_queued_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_reset_queued_resource(self, response): + logging.log(f"Received response: {response}") + return response + def pre_start_node(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -203,6 +243,31 @@ def post_create_node( """ return response + def pre_create_queued_resource( + self, + request: cloud_tpu.CreateQueuedResourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_tpu.CreateQueuedResourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_queued_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tpu server. + """ + return request, metadata + + def post_create_queued_resource( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_queued_resource + + Override in a subclass to manipulate the response + after it is returned by the Tpu server but before + it is returned to user code. + """ + return response + def pre_delete_node( self, request: cloud_tpu.DeleteNodeRequest, @@ -226,6 +291,31 @@ def post_delete_node( """ return response + def pre_delete_queued_resource( + self, + request: cloud_tpu.DeleteQueuedResourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_tpu.DeleteQueuedResourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_queued_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tpu server. + """ + return request, metadata + + def post_delete_queued_resource( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_queued_resource + + Override in a subclass to manipulate the response + after it is returned by the Tpu server but before + it is returned to user code. + """ + return response + def pre_generate_service_identity( self, request: cloud_tpu.GenerateServiceIdentityRequest, @@ -323,6 +413,31 @@ def post_get_node(self, response: cloud_tpu.Node) -> cloud_tpu.Node: """ return response + def pre_get_queued_resource( + self, + request: cloud_tpu.GetQueuedResourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_tpu.GetQueuedResourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_queued_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tpu server. + """ + return request, metadata + + def post_get_queued_resource( + self, response: cloud_tpu.QueuedResource + ) -> cloud_tpu.QueuedResource: + """Post-rpc interceptor for get_queued_resource + + Override in a subclass to manipulate the response + after it is returned by the Tpu server but before + it is returned to user code. + """ + return response + def pre_get_runtime_version( self, request: cloud_tpu.GetRuntimeVersionRequest, @@ -396,6 +511,31 @@ def post_list_nodes( """ return response + def pre_list_queued_resources( + self, + request: cloud_tpu.ListQueuedResourcesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_tpu.ListQueuedResourcesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_queued_resources + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tpu server. + """ + return request, metadata + + def post_list_queued_resources( + self, response: cloud_tpu.ListQueuedResourcesResponse + ) -> cloud_tpu.ListQueuedResourcesResponse: + """Post-rpc interceptor for list_queued_resources + + Override in a subclass to manipulate the response + after it is returned by the Tpu server but before + it is returned to user code. + """ + return response + def pre_list_runtime_versions( self, request: cloud_tpu.ListRuntimeVersionsRequest, @@ -421,6 +561,31 @@ def post_list_runtime_versions( """ return response + def pre_reset_queued_resource( + self, + request: cloud_tpu.ResetQueuedResourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_tpu.ResetQueuedResourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for reset_queued_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tpu server. + """ + return request, metadata + + def post_reset_queued_resource( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for reset_queued_resource + + Override in a subclass to manipulate the response + after it is returned by the Tpu server but before + it is returned to user code. + """ + return response + def pre_start_node( self, request: cloud_tpu.StartNodeRequest, @@ -924,9 +1089,11 @@ def __call__( ) return resp - class _DeleteNode(_BaseTpuRestTransport._BaseDeleteNode, TpuRestStub): + class _CreateQueuedResource( + _BaseTpuRestTransport._BaseCreateQueuedResource, TpuRestStub + ): def __hash__(self): - return hash("TpuRestTransport.DeleteNode") + return hash("TpuRestTransport.CreateQueuedResource") @staticmethod def _get_response( @@ -947,23 +1114,24 @@ 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_tpu.DeleteNodeRequest, + request: cloud_tpu.CreateQueuedResourceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the delete node method over HTTP. + r"""Call the create queued resource method over HTTP. Args: - request (~.cloud_tpu.DeleteNodeRequest): + request (~.cloud_tpu.CreateQueuedResourceRequest): The request object. Request for - [DeleteNode][google.cloud.tpu.v2.Tpu.DeleteNode]. + [CreateQueuedResource][google.cloud.tpu.v2.Tpu.CreateQueuedResource]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -980,18 +1148,30 @@ def __call__( """ - http_options = _BaseTpuRestTransport._BaseDeleteNode._get_http_options() + http_options = ( + _BaseTpuRestTransport._BaseCreateQueuedResource._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_node(request, metadata) + request, metadata = self._interceptor.pre_create_queued_resource( + request, metadata + ) transcoded_request = ( - _BaseTpuRestTransport._BaseDeleteNode._get_transcoded_request( + _BaseTpuRestTransport._BaseCreateQueuedResource._get_transcoded_request( http_options, request ) ) + body = ( + _BaseTpuRestTransport._BaseCreateQueuedResource._get_request_body_json( + transcoded_request + ) + ) + # Jsonify the query params - query_params = _BaseTpuRestTransport._BaseDeleteNode._get_query_params_json( - transcoded_request + query_params = ( + _BaseTpuRestTransport._BaseCreateQueuedResource._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1012,23 +1192,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.tpu_v2.TpuClient.DeleteNode", + f"Sending request for google.cloud.tpu_v2.TpuClient.CreateQueuedResource", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "DeleteNode", + "rpcName": "CreateQueuedResource", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = TpuRestTransport._DeleteNode._get_response( + response = TpuRestTransport._CreateQueuedResource._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1040,7 +1221,7 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_node(resp) + resp = self._interceptor.post_create_queued_resource(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER @@ -1054,21 +1235,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.tpu_v2.TpuClient.delete_node", + "Received response for google.cloud.tpu_v2.TpuClient.create_queued_resource", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "DeleteNode", + "rpcName": "CreateQueuedResource", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GenerateServiceIdentity( - _BaseTpuRestTransport._BaseGenerateServiceIdentity, TpuRestStub - ): + class _DeleteNode(_BaseTpuRestTransport._BaseDeleteNode, TpuRestStub): def __hash__(self): - return hash("TpuRestTransport.GenerateServiceIdentity") + return hash("TpuRestTransport.DeleteNode") @staticmethod def _get_response( @@ -1089,24 +1268,23 @@ 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_tpu.GenerateServiceIdentityRequest, + request: cloud_tpu.DeleteNodeRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_tpu.GenerateServiceIdentityResponse: - r"""Call the generate service identity method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the delete node method over HTTP. Args: - request (~.cloud_tpu.GenerateServiceIdentityRequest): + request (~.cloud_tpu.DeleteNodeRequest): The request object. Request for - [GenerateServiceIdentity][google.cloud.tpu.v2.Tpu.GenerateServiceIdentity]. + [DeleteNode][google.cloud.tpu.v2.Tpu.DeleteNode]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1116,29 +1294,24 @@ def __call__( be of type `bytes`. Returns: - ~.cloud_tpu.GenerateServiceIdentityResponse: - Response for - [GenerateServiceIdentity][google.cloud.tpu.v2.Tpu.GenerateServiceIdentity]. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseTpuRestTransport._BaseGenerateServiceIdentity._get_http_options() - ) - - request, metadata = self._interceptor.pre_generate_service_identity( - request, metadata - ) - transcoded_request = _BaseTpuRestTransport._BaseGenerateServiceIdentity._get_transcoded_request( - http_options, request - ) + http_options = _BaseTpuRestTransport._BaseDeleteNode._get_http_options() - body = _BaseTpuRestTransport._BaseGenerateServiceIdentity._get_request_body_json( - transcoded_request + request, metadata = self._interceptor.pre_delete_node(request, metadata) + transcoded_request = ( + _BaseTpuRestTransport._BaseDeleteNode._get_transcoded_request( + http_options, request + ) ) # Jsonify the query params - query_params = _BaseTpuRestTransport._BaseGenerateServiceIdentity._get_query_params_json( + query_params = _BaseTpuRestTransport._BaseDeleteNode._get_query_params_json( transcoded_request ) @@ -1150,7 +1323,7 @@ def __call__( ) method = transcoded_request["method"] try: - request_payload = type(request).to_json(request) + request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { @@ -1160,24 +1333,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.tpu_v2.TpuClient.GenerateServiceIdentity", + f"Sending request for google.cloud.tpu_v2.TpuClient.DeleteNode", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "GenerateServiceIdentity", + "rpcName": "DeleteNode", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = TpuRestTransport._GenerateServiceIdentity._get_response( + response = TpuRestTransport._DeleteNode._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1186,19 +1358,15 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = cloud_tpu.GenerateServiceIdentityResponse() - pb_resp = cloud_tpu.GenerateServiceIdentityResponse.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_generate_service_identity(resp) + resp = self._interceptor.post_delete_node(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - cloud_tpu.GenerateServiceIdentityResponse.to_json(response) - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1207,21 +1375,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.tpu_v2.TpuClient.generate_service_identity", + "Received response for google.cloud.tpu_v2.TpuClient.delete_node", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "GenerateServiceIdentity", + "rpcName": "DeleteNode", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetAcceleratorType( - _BaseTpuRestTransport._BaseGetAcceleratorType, TpuRestStub + class _DeleteQueuedResource( + _BaseTpuRestTransport._BaseDeleteQueuedResource, TpuRestStub ): def __hash__(self): - return hash("TpuRestTransport.GetAcceleratorType") + return hash("TpuRestTransport.DeleteQueuedResource") @staticmethod def _get_response( @@ -1247,18 +1415,18 @@ def _get_response( def __call__( self, - request: cloud_tpu.GetAcceleratorTypeRequest, + request: cloud_tpu.DeleteQueuedResourceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_tpu.AcceleratorType: - r"""Call the get accelerator type method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the delete queued resource method over HTTP. Args: - request (~.cloud_tpu.GetAcceleratorTypeRequest): + request (~.cloud_tpu.DeleteQueuedResourceRequest): The request object. Request for - [GetAcceleratorType][google.cloud.tpu.v2.Tpu.GetAcceleratorType]. + [DeleteQueuedResource][google.cloud.tpu.v2.Tpu.DeleteQueuedResource]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1268,28 +1436,29 @@ def __call__( be of type `bytes`. Returns: - ~.cloud_tpu.AcceleratorType: - A accelerator type that a Node can be - configured with. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseTpuRestTransport._BaseGetAcceleratorType._get_http_options() + _BaseTpuRestTransport._BaseDeleteQueuedResource._get_http_options() ) - request, metadata = self._interceptor.pre_get_accelerator_type( + request, metadata = self._interceptor.pre_delete_queued_resource( request, metadata ) transcoded_request = ( - _BaseTpuRestTransport._BaseGetAcceleratorType._get_transcoded_request( + _BaseTpuRestTransport._BaseDeleteQueuedResource._get_transcoded_request( http_options, request ) ) # Jsonify the query params query_params = ( - _BaseTpuRestTransport._BaseGetAcceleratorType._get_query_params_json( + _BaseTpuRestTransport._BaseDeleteQueuedResource._get_query_params_json( transcoded_request ) ) @@ -1302,7 +1471,7 @@ def __call__( ) method = transcoded_request["method"] try: - request_payload = type(request).to_json(request) + request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { @@ -1312,17 +1481,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.tpu_v2.TpuClient.GetAcceleratorType", + f"Sending request for google.cloud.tpu_v2.TpuClient.DeleteQueuedResource", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "GetAcceleratorType", + "rpcName": "DeleteQueuedResource", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = TpuRestTransport._GetAcceleratorType._get_response( + response = TpuRestTransport._DeleteQueuedResource._get_response( self._host, metadata, query_params, @@ -1337,17 +1506,15 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = cloud_tpu.AcceleratorType() - pb_resp = cloud_tpu.AcceleratorType.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_accelerator_type(resp) + resp = self._interceptor.post_delete_queued_resource(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = cloud_tpu.AcceleratorType.to_json(response) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1356,21 +1523,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.tpu_v2.TpuClient.get_accelerator_type", + "Received response for google.cloud.tpu_v2.TpuClient.delete_queued_resource", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "GetAcceleratorType", + "rpcName": "DeleteQueuedResource", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetGuestAttributes( - _BaseTpuRestTransport._BaseGetGuestAttributes, TpuRestStub + class _GenerateServiceIdentity( + _BaseTpuRestTransport._BaseGenerateServiceIdentity, TpuRestStub ): def __hash__(self): - return hash("TpuRestTransport.GetGuestAttributes") + return hash("TpuRestTransport.GenerateServiceIdentity") @staticmethod def _get_response( @@ -1397,18 +1564,18 @@ def _get_response( def __call__( self, - request: cloud_tpu.GetGuestAttributesRequest, + request: cloud_tpu.GenerateServiceIdentityRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_tpu.GetGuestAttributesResponse: - r"""Call the get guest attributes method over HTTP. + ) -> cloud_tpu.GenerateServiceIdentityResponse: + r"""Call the generate service identity method over HTTP. Args: - request (~.cloud_tpu.GetGuestAttributesRequest): + request (~.cloud_tpu.GenerateServiceIdentityRequest): The request object. Request for - [GetGuestAttributes][google.cloud.tpu.v2.Tpu.GetGuestAttributes]. + [GenerateServiceIdentity][google.cloud.tpu.v2.Tpu.GenerateServiceIdentity]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1418,32 +1585,180 @@ def __call__( be of type `bytes`. Returns: - ~.cloud_tpu.GetGuestAttributesResponse: + ~.cloud_tpu.GenerateServiceIdentityResponse: Response for - [GetGuestAttributes][google.cloud.tpu.v2.Tpu.GetGuestAttributes]. + [GenerateServiceIdentity][google.cloud.tpu.v2.Tpu.GenerateServiceIdentity]. """ http_options = ( - _BaseTpuRestTransport._BaseGetGuestAttributes._get_http_options() + _BaseTpuRestTransport._BaseGenerateServiceIdentity._get_http_options() ) - request, metadata = self._interceptor.pre_get_guest_attributes( + request, metadata = self._interceptor.pre_generate_service_identity( request, metadata ) - transcoded_request = ( - _BaseTpuRestTransport._BaseGetGuestAttributes._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseTpuRestTransport._BaseGenerateServiceIdentity._get_transcoded_request( + http_options, request ) - body = _BaseTpuRestTransport._BaseGetGuestAttributes._get_request_body_json( + body = _BaseTpuRestTransport._BaseGenerateServiceIdentity._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseTpuRestTransport._BaseGenerateServiceIdentity._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.tpu_v2.TpuClient.GenerateServiceIdentity", + extra={ + "serviceName": "google.cloud.tpu.v2.Tpu", + "rpcName": "GenerateServiceIdentity", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TpuRestTransport._GenerateServiceIdentity._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 = cloud_tpu.GenerateServiceIdentityResponse() + pb_resp = cloud_tpu.GenerateServiceIdentityResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_service_identity(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + cloud_tpu.GenerateServiceIdentityResponse.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.tpu_v2.TpuClient.generate_service_identity", + extra={ + "serviceName": "google.cloud.tpu.v2.Tpu", + "rpcName": "GenerateServiceIdentity", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAcceleratorType( + _BaseTpuRestTransport._BaseGetAcceleratorType, TpuRestStub + ): + def __hash__(self): + return hash("TpuRestTransport.GetAcceleratorType") + + @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_tpu.GetAcceleratorTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_tpu.AcceleratorType: + r"""Call the get accelerator type method over HTTP. + + Args: + request (~.cloud_tpu.GetAcceleratorTypeRequest): + The request object. Request for + [GetAcceleratorType][google.cloud.tpu.v2.Tpu.GetAcceleratorType]. + retry (google.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_tpu.AcceleratorType: + A accelerator type that a Node can be + configured with. + + """ + + http_options = ( + _BaseTpuRestTransport._BaseGetAcceleratorType._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_accelerator_type( + request, metadata + ) + transcoded_request = ( + _BaseTpuRestTransport._BaseGetAcceleratorType._get_transcoded_request( + http_options, request + ) + ) + # Jsonify the query params query_params = ( - _BaseTpuRestTransport._BaseGetGuestAttributes._get_query_params_json( + _BaseTpuRestTransport._BaseGetAcceleratorType._get_query_params_json( transcoded_request ) ) @@ -1466,24 +1781,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.tpu_v2.TpuClient.GetGuestAttributes", + f"Sending request for google.cloud.tpu_v2.TpuClient.GetAcceleratorType", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "GetGuestAttributes", + "rpcName": "GetAcceleratorType", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = TpuRestTransport._GetGuestAttributes._get_response( + response = TpuRestTransport._GetAcceleratorType._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1492,19 +1806,17 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = cloud_tpu.GetGuestAttributesResponse() - pb_resp = cloud_tpu.GetGuestAttributesResponse.pb(resp) + resp = cloud_tpu.AcceleratorType() + pb_resp = cloud_tpu.AcceleratorType.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_guest_attributes(resp) + resp = self._interceptor.post_get_accelerator_type(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = cloud_tpu.GetGuestAttributesResponse.to_json( - response - ) + response_payload = cloud_tpu.AcceleratorType.to_json(response) except: response_payload = None http_response = { @@ -1513,19 +1825,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.tpu_v2.TpuClient.get_guest_attributes", + "Received response for google.cloud.tpu_v2.TpuClient.get_accelerator_type", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "GetGuestAttributes", + "rpcName": "GetAcceleratorType", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetNode(_BaseTpuRestTransport._BaseGetNode, TpuRestStub): + class _GetGuestAttributes( + _BaseTpuRestTransport._BaseGetGuestAttributes, TpuRestStub + ): def __hash__(self): - return hash("TpuRestTransport.GetNode") + return hash("TpuRestTransport.GetGuestAttributes") @staticmethod def _get_response( @@ -1546,22 +1860,614 @@ 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_tpu.GetNodeRequest, + request: cloud_tpu.GetGuestAttributesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_tpu.GetGuestAttributesResponse: + r"""Call the get guest attributes method over HTTP. + + Args: + request (~.cloud_tpu.GetGuestAttributesRequest): + The request object. Request for + [GetGuestAttributes][google.cloud.tpu.v2.Tpu.GetGuestAttributes]. + retry (google.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_tpu.GetGuestAttributesResponse: + Response for + [GetGuestAttributes][google.cloud.tpu.v2.Tpu.GetGuestAttributes]. + + """ + + http_options = ( + _BaseTpuRestTransport._BaseGetGuestAttributes._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_guest_attributes( + request, metadata + ) + transcoded_request = ( + _BaseTpuRestTransport._BaseGetGuestAttributes._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseTpuRestTransport._BaseGetGuestAttributes._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseTpuRestTransport._BaseGetGuestAttributes._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.tpu_v2.TpuClient.GetGuestAttributes", + extra={ + "serviceName": "google.cloud.tpu.v2.Tpu", + "rpcName": "GetGuestAttributes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TpuRestTransport._GetGuestAttributes._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 = cloud_tpu.GetGuestAttributesResponse() + pb_resp = cloud_tpu.GetGuestAttributesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_guest_attributes(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_tpu.GetGuestAttributesResponse.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.tpu_v2.TpuClient.get_guest_attributes", + extra={ + "serviceName": "google.cloud.tpu.v2.Tpu", + "rpcName": "GetGuestAttributes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetNode(_BaseTpuRestTransport._BaseGetNode, TpuRestStub): + def __hash__(self): + return hash("TpuRestTransport.GetNode") + + @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_tpu.GetNodeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_tpu.Node: + r"""Call the get node method over HTTP. + + Args: + request (~.cloud_tpu.GetNodeRequest): + The request object. Request for [GetNode][google.cloud.tpu.v2.Tpu.GetNode]. + retry (google.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_tpu.Node: + A TPU instance. + """ + + http_options = _BaseTpuRestTransport._BaseGetNode._get_http_options() + + request, metadata = self._interceptor.pre_get_node(request, metadata) + transcoded_request = ( + _BaseTpuRestTransport._BaseGetNode._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseTpuRestTransport._BaseGetNode._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.tpu_v2.TpuClient.GetNode", + extra={ + "serviceName": "google.cloud.tpu.v2.Tpu", + "rpcName": "GetNode", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TpuRestTransport._GetNode._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_tpu.Node() + pb_resp = cloud_tpu.Node.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_node(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_tpu.Node.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.tpu_v2.TpuClient.get_node", + extra={ + "serviceName": "google.cloud.tpu.v2.Tpu", + "rpcName": "GetNode", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQueuedResource(_BaseTpuRestTransport._BaseGetQueuedResource, TpuRestStub): + def __hash__(self): + return hash("TpuRestTransport.GetQueuedResource") + + @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_tpu.GetQueuedResourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_tpu.QueuedResource: + r"""Call the get queued resource method over HTTP. + + Args: + request (~.cloud_tpu.GetQueuedResourceRequest): + The request object. Request for + [GetQueuedResource][google.cloud.tpu.v2.Tpu.GetQueuedResource] + retry (google.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_tpu.QueuedResource: + A QueuedResource represents a request + for resources that will be placed in a + queue and fulfilled when the necessary + resources are available. + + """ + + http_options = ( + _BaseTpuRestTransport._BaseGetQueuedResource._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_queued_resource( + request, metadata + ) + transcoded_request = ( + _BaseTpuRestTransport._BaseGetQueuedResource._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseTpuRestTransport._BaseGetQueuedResource._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.tpu_v2.TpuClient.GetQueuedResource", + extra={ + "serviceName": "google.cloud.tpu.v2.Tpu", + "rpcName": "GetQueuedResource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TpuRestTransport._GetQueuedResource._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_tpu.QueuedResource() + pb_resp = cloud_tpu.QueuedResource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_queued_resource(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_tpu.QueuedResource.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.tpu_v2.TpuClient.get_queued_resource", + extra={ + "serviceName": "google.cloud.tpu.v2.Tpu", + "rpcName": "GetQueuedResource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRuntimeVersion(_BaseTpuRestTransport._BaseGetRuntimeVersion, TpuRestStub): + def __hash__(self): + return hash("TpuRestTransport.GetRuntimeVersion") + + @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_tpu.GetRuntimeVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_tpu.RuntimeVersion: + r"""Call the get runtime version method over HTTP. + + Args: + request (~.cloud_tpu.GetRuntimeVersionRequest): + The request object. Request for + [GetRuntimeVersion][google.cloud.tpu.v2.Tpu.GetRuntimeVersion]. + retry (google.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_tpu.RuntimeVersion: + A runtime version that a Node can be + configured with. + + """ + + http_options = ( + _BaseTpuRestTransport._BaseGetRuntimeVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_runtime_version( + request, metadata + ) + transcoded_request = ( + _BaseTpuRestTransport._BaseGetRuntimeVersion._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseTpuRestTransport._BaseGetRuntimeVersion._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.tpu_v2.TpuClient.GetRuntimeVersion", + extra={ + "serviceName": "google.cloud.tpu.v2.Tpu", + "rpcName": "GetRuntimeVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TpuRestTransport._GetRuntimeVersion._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_tpu.RuntimeVersion() + pb_resp = cloud_tpu.RuntimeVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_runtime_version(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_tpu.RuntimeVersion.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.tpu_v2.TpuClient.get_runtime_version", + extra={ + "serviceName": "google.cloud.tpu.v2.Tpu", + "rpcName": "GetRuntimeVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAcceleratorTypes( + _BaseTpuRestTransport._BaseListAcceleratorTypes, TpuRestStub + ): + def __hash__(self): + return hash("TpuRestTransport.ListAcceleratorTypes") + + @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_tpu.ListAcceleratorTypesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_tpu.Node: - r"""Call the get node method over HTTP. + ) -> cloud_tpu.ListAcceleratorTypesResponse: + r"""Call the list accelerator types method over HTTP. Args: - request (~.cloud_tpu.GetNodeRequest): - The request object. Request for [GetNode][google.cloud.tpu.v2.Tpu.GetNode]. + request (~.cloud_tpu.ListAcceleratorTypesRequest): + The request object. Request for + [ListAcceleratorTypes][google.cloud.tpu.v2.Tpu.ListAcceleratorTypes]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1571,22 +2477,30 @@ def __call__( be of type `bytes`. Returns: - ~.cloud_tpu.Node: - A TPU instance. + ~.cloud_tpu.ListAcceleratorTypesResponse: + Response for + [ListAcceleratorTypes][google.cloud.tpu.v2.Tpu.ListAcceleratorTypes]. + """ - http_options = _BaseTpuRestTransport._BaseGetNode._get_http_options() + http_options = ( + _BaseTpuRestTransport._BaseListAcceleratorTypes._get_http_options() + ) - request, metadata = self._interceptor.pre_get_node(request, metadata) + request, metadata = self._interceptor.pre_list_accelerator_types( + request, metadata + ) transcoded_request = ( - _BaseTpuRestTransport._BaseGetNode._get_transcoded_request( + _BaseTpuRestTransport._BaseListAcceleratorTypes._get_transcoded_request( http_options, request ) ) # Jsonify the query params - query_params = _BaseTpuRestTransport._BaseGetNode._get_query_params_json( - transcoded_request + query_params = ( + _BaseTpuRestTransport._BaseListAcceleratorTypes._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1607,17 +2521,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.tpu_v2.TpuClient.GetNode", + f"Sending request for google.cloud.tpu_v2.TpuClient.ListAcceleratorTypes", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "GetNode", + "rpcName": "ListAcceleratorTypes", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = TpuRestTransport._GetNode._get_response( + response = TpuRestTransport._ListAcceleratorTypes._get_response( self._host, metadata, query_params, @@ -1632,17 +2546,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = cloud_tpu.Node() - pb_resp = cloud_tpu.Node.pb(resp) + resp = cloud_tpu.ListAcceleratorTypesResponse() + pb_resp = cloud_tpu.ListAcceleratorTypesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_node(resp) + resp = self._interceptor.post_list_accelerator_types(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = cloud_tpu.Node.to_json(response) + response_payload = cloud_tpu.ListAcceleratorTypesResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -1651,19 +2567,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.tpu_v2.TpuClient.get_node", + "Received response for google.cloud.tpu_v2.TpuClient.list_accelerator_types", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "GetNode", + "rpcName": "ListAcceleratorTypes", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetRuntimeVersion(_BaseTpuRestTransport._BaseGetRuntimeVersion, TpuRestStub): + class _ListNodes(_BaseTpuRestTransport._BaseListNodes, TpuRestStub): def __hash__(self): - return hash("TpuRestTransport.GetRuntimeVersion") + return hash("TpuRestTransport.ListNodes") @staticmethod def _get_response( @@ -1689,18 +2605,18 @@ def _get_response( def __call__( self, - request: cloud_tpu.GetRuntimeVersionRequest, + request: cloud_tpu.ListNodesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_tpu.RuntimeVersion: - r"""Call the get runtime version method over HTTP. + ) -> cloud_tpu.ListNodesResponse: + r"""Call the list nodes method over HTTP. Args: - request (~.cloud_tpu.GetRuntimeVersionRequest): + request (~.cloud_tpu.ListNodesRequest): The request object. Request for - [GetRuntimeVersion][google.cloud.tpu.v2.Tpu.GetRuntimeVersion]. + [ListNodes][google.cloud.tpu.v2.Tpu.ListNodes]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1710,30 +2626,24 @@ def __call__( be of type `bytes`. Returns: - ~.cloud_tpu.RuntimeVersion: - A runtime version that a Node can be - configured with. + ~.cloud_tpu.ListNodesResponse: + Response for + [ListNodes][google.cloud.tpu.v2.Tpu.ListNodes]. """ - http_options = ( - _BaseTpuRestTransport._BaseGetRuntimeVersion._get_http_options() - ) + http_options = _BaseTpuRestTransport._BaseListNodes._get_http_options() - request, metadata = self._interceptor.pre_get_runtime_version( - request, metadata - ) + request, metadata = self._interceptor.pre_list_nodes(request, metadata) transcoded_request = ( - _BaseTpuRestTransport._BaseGetRuntimeVersion._get_transcoded_request( + _BaseTpuRestTransport._BaseListNodes._get_transcoded_request( http_options, request ) ) # Jsonify the query params - query_params = ( - _BaseTpuRestTransport._BaseGetRuntimeVersion._get_query_params_json( - transcoded_request - ) + query_params = _BaseTpuRestTransport._BaseListNodes._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1754,17 +2664,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.tpu_v2.TpuClient.GetRuntimeVersion", + f"Sending request for google.cloud.tpu_v2.TpuClient.ListNodes", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "GetRuntimeVersion", + "rpcName": "ListNodes", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = TpuRestTransport._GetRuntimeVersion._get_response( + response = TpuRestTransport._ListNodes._get_response( self._host, metadata, query_params, @@ -1779,17 +2689,17 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = cloud_tpu.RuntimeVersion() - pb_resp = cloud_tpu.RuntimeVersion.pb(resp) + resp = cloud_tpu.ListNodesResponse() + pb_resp = cloud_tpu.ListNodesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_runtime_version(resp) + resp = self._interceptor.post_list_nodes(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = cloud_tpu.RuntimeVersion.to_json(response) + response_payload = cloud_tpu.ListNodesResponse.to_json(response) except: response_payload = None http_response = { @@ -1798,21 +2708,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.tpu_v2.TpuClient.get_runtime_version", + "Received response for google.cloud.tpu_v2.TpuClient.list_nodes", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "GetRuntimeVersion", + "rpcName": "ListNodes", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListAcceleratorTypes( - _BaseTpuRestTransport._BaseListAcceleratorTypes, TpuRestStub + class _ListQueuedResources( + _BaseTpuRestTransport._BaseListQueuedResources, TpuRestStub ): def __hash__(self): - return hash("TpuRestTransport.ListAcceleratorTypes") + return hash("TpuRestTransport.ListQueuedResources") @staticmethod def _get_response( @@ -1838,18 +2748,18 @@ def _get_response( def __call__( self, - request: cloud_tpu.ListAcceleratorTypesRequest, + request: cloud_tpu.ListQueuedResourcesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_tpu.ListAcceleratorTypesResponse: - r"""Call the list accelerator types method over HTTP. + ) -> cloud_tpu.ListQueuedResourcesResponse: + r"""Call the list queued resources method over HTTP. Args: - request (~.cloud_tpu.ListAcceleratorTypesRequest): + request (~.cloud_tpu.ListQueuedResourcesRequest): The request object. Request for - [ListAcceleratorTypes][google.cloud.tpu.v2.Tpu.ListAcceleratorTypes]. + [ListQueuedResources][google.cloud.tpu.v2.Tpu.ListQueuedResources]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1859,28 +2769,28 @@ def __call__( be of type `bytes`. Returns: - ~.cloud_tpu.ListAcceleratorTypesResponse: + ~.cloud_tpu.ListQueuedResourcesResponse: Response for - [ListAcceleratorTypes][google.cloud.tpu.v2.Tpu.ListAcceleratorTypes]. + [ListQueuedResources][google.cloud.tpu.v2.Tpu.ListQueuedResources]. """ http_options = ( - _BaseTpuRestTransport._BaseListAcceleratorTypes._get_http_options() + _BaseTpuRestTransport._BaseListQueuedResources._get_http_options() ) - request, metadata = self._interceptor.pre_list_accelerator_types( + request, metadata = self._interceptor.pre_list_queued_resources( request, metadata ) transcoded_request = ( - _BaseTpuRestTransport._BaseListAcceleratorTypes._get_transcoded_request( + _BaseTpuRestTransport._BaseListQueuedResources._get_transcoded_request( http_options, request ) ) # Jsonify the query params query_params = ( - _BaseTpuRestTransport._BaseListAcceleratorTypes._get_query_params_json( + _BaseTpuRestTransport._BaseListQueuedResources._get_query_params_json( transcoded_request ) ) @@ -1903,17 +2813,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.tpu_v2.TpuClient.ListAcceleratorTypes", + f"Sending request for google.cloud.tpu_v2.TpuClient.ListQueuedResources", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "ListAcceleratorTypes", + "rpcName": "ListQueuedResources", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = TpuRestTransport._ListAcceleratorTypes._get_response( + response = TpuRestTransport._ListQueuedResources._get_response( self._host, metadata, query_params, @@ -1928,17 +2838,17 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = cloud_tpu.ListAcceleratorTypesResponse() - pb_resp = cloud_tpu.ListAcceleratorTypesResponse.pb(resp) + resp = cloud_tpu.ListQueuedResourcesResponse() + pb_resp = cloud_tpu.ListQueuedResourcesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_accelerator_types(resp) + resp = self._interceptor.post_list_queued_resources(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = cloud_tpu.ListAcceleratorTypesResponse.to_json( + response_payload = cloud_tpu.ListQueuedResourcesResponse.to_json( response ) except: @@ -1949,19 +2859,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.tpu_v2.TpuClient.list_accelerator_types", + "Received response for google.cloud.tpu_v2.TpuClient.list_queued_resources", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "ListAcceleratorTypes", + "rpcName": "ListQueuedResources", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListNodes(_BaseTpuRestTransport._BaseListNodes, TpuRestStub): + class _ListRuntimeVersions( + _BaseTpuRestTransport._BaseListRuntimeVersions, TpuRestStub + ): def __hash__(self): - return hash("TpuRestTransport.ListNodes") + return hash("TpuRestTransport.ListRuntimeVersions") @staticmethod def _get_response( @@ -1987,18 +2899,18 @@ def _get_response( def __call__( self, - request: cloud_tpu.ListNodesRequest, + request: cloud_tpu.ListRuntimeVersionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_tpu.ListNodesResponse: - r"""Call the list nodes method over HTTP. + ) -> cloud_tpu.ListRuntimeVersionsResponse: + r"""Call the list runtime versions method over HTTP. Args: - request (~.cloud_tpu.ListNodesRequest): + request (~.cloud_tpu.ListRuntimeVersionsRequest): The request object. Request for - [ListNodes][google.cloud.tpu.v2.Tpu.ListNodes]. + [ListRuntimeVersions][google.cloud.tpu.v2.Tpu.ListRuntimeVersions]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2008,24 +2920,30 @@ def __call__( be of type `bytes`. Returns: - ~.cloud_tpu.ListNodesResponse: + ~.cloud_tpu.ListRuntimeVersionsResponse: Response for - [ListNodes][google.cloud.tpu.v2.Tpu.ListNodes]. + [ListRuntimeVersions][google.cloud.tpu.v2.Tpu.ListRuntimeVersions]. """ - http_options = _BaseTpuRestTransport._BaseListNodes._get_http_options() + http_options = ( + _BaseTpuRestTransport._BaseListRuntimeVersions._get_http_options() + ) - request, metadata = self._interceptor.pre_list_nodes(request, metadata) + request, metadata = self._interceptor.pre_list_runtime_versions( + request, metadata + ) transcoded_request = ( - _BaseTpuRestTransport._BaseListNodes._get_transcoded_request( + _BaseTpuRestTransport._BaseListRuntimeVersions._get_transcoded_request( http_options, request ) ) # Jsonify the query params - query_params = _BaseTpuRestTransport._BaseListNodes._get_query_params_json( - transcoded_request + query_params = ( + _BaseTpuRestTransport._BaseListRuntimeVersions._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -2046,17 +2964,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.tpu_v2.TpuClient.ListNodes", + f"Sending request for google.cloud.tpu_v2.TpuClient.ListRuntimeVersions", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "ListNodes", + "rpcName": "ListRuntimeVersions", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = TpuRestTransport._ListNodes._get_response( + response = TpuRestTransport._ListRuntimeVersions._get_response( self._host, metadata, query_params, @@ -2071,17 +2989,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = cloud_tpu.ListNodesResponse() - pb_resp = cloud_tpu.ListNodesResponse.pb(resp) + resp = cloud_tpu.ListRuntimeVersionsResponse() + pb_resp = cloud_tpu.ListRuntimeVersionsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_nodes(resp) + resp = self._interceptor.post_list_runtime_versions(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = cloud_tpu.ListNodesResponse.to_json(response) + response_payload = cloud_tpu.ListRuntimeVersionsResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -2090,21 +3010,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.tpu_v2.TpuClient.list_nodes", + "Received response for google.cloud.tpu_v2.TpuClient.list_runtime_versions", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "ListNodes", + "rpcName": "ListRuntimeVersions", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListRuntimeVersions( - _BaseTpuRestTransport._BaseListRuntimeVersions, TpuRestStub + class _ResetQueuedResource( + _BaseTpuRestTransport._BaseResetQueuedResource, TpuRestStub ): def __hash__(self): - return hash("TpuRestTransport.ListRuntimeVersions") + return hash("TpuRestTransport.ResetQueuedResource") @staticmethod def _get_response( @@ -2125,23 +3045,24 @@ 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_tpu.ListRuntimeVersionsRequest, + request: cloud_tpu.ResetQueuedResourceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_tpu.ListRuntimeVersionsResponse: - r"""Call the list runtime versions method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the reset queued resource method over HTTP. Args: - request (~.cloud_tpu.ListRuntimeVersionsRequest): + request (~.cloud_tpu.ResetQueuedResourceRequest): The request object. Request for - [ListRuntimeVersions][google.cloud.tpu.v2.Tpu.ListRuntimeVersions]. + [ResetQueuedResource][google.cloud.tpu.v2.Tpu.ResetQueuedResource]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2151,28 +3072,35 @@ def __call__( be of type `bytes`. Returns: - ~.cloud_tpu.ListRuntimeVersionsResponse: - Response for - [ListRuntimeVersions][google.cloud.tpu.v2.Tpu.ListRuntimeVersions]. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseTpuRestTransport._BaseListRuntimeVersions._get_http_options() + _BaseTpuRestTransport._BaseResetQueuedResource._get_http_options() ) - request, metadata = self._interceptor.pre_list_runtime_versions( + request, metadata = self._interceptor.pre_reset_queued_resource( request, metadata ) transcoded_request = ( - _BaseTpuRestTransport._BaseListRuntimeVersions._get_transcoded_request( + _BaseTpuRestTransport._BaseResetQueuedResource._get_transcoded_request( http_options, request ) ) + body = ( + _BaseTpuRestTransport._BaseResetQueuedResource._get_request_body_json( + transcoded_request + ) + ) + # Jsonify the query params query_params = ( - _BaseTpuRestTransport._BaseListRuntimeVersions._get_query_params_json( + _BaseTpuRestTransport._BaseResetQueuedResource._get_query_params_json( transcoded_request ) ) @@ -2185,7 +3113,7 @@ def __call__( ) method = transcoded_request["method"] try: - request_payload = type(request).to_json(request) + request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { @@ -2195,23 +3123,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.tpu_v2.TpuClient.ListRuntimeVersions", + f"Sending request for google.cloud.tpu_v2.TpuClient.ResetQueuedResource", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "ListRuntimeVersions", + "rpcName": "ResetQueuedResource", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = TpuRestTransport._ListRuntimeVersions._get_response( + response = TpuRestTransport._ResetQueuedResource._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2220,19 +3149,15 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = cloud_tpu.ListRuntimeVersionsResponse() - pb_resp = cloud_tpu.ListRuntimeVersionsResponse.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_list_runtime_versions(resp) + resp = self._interceptor.post_reset_queued_resource(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = cloud_tpu.ListRuntimeVersionsResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -2241,10 +3166,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.tpu_v2.TpuClient.list_runtime_versions", + "Received response for google.cloud.tpu_v2.TpuClient.reset_queued_resource", extra={ "serviceName": "google.cloud.tpu.v2.Tpu", - "rpcName": "ListRuntimeVersions", + "rpcName": "ResetQueuedResource", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -2697,6 +3622,14 @@ def create_node( # In C++ this would require a dynamic_cast return self._CreateNode(self._session, self._host, self._interceptor) # type: ignore + @property + def create_queued_resource( + self, + ) -> Callable[[cloud_tpu.CreateQueuedResourceRequest], 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._CreateQueuedResource(self._session, self._host, self._interceptor) # type: ignore + @property def delete_node( self, @@ -2705,6 +3638,14 @@ def delete_node( # In C++ this would require a dynamic_cast return self._DeleteNode(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_queued_resource( + self, + ) -> Callable[[cloud_tpu.DeleteQueuedResourceRequest], 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._DeleteQueuedResource(self._session, self._host, self._interceptor) # type: ignore + @property def generate_service_identity( self, @@ -2740,6 +3681,14 @@ def get_node(self) -> Callable[[cloud_tpu.GetNodeRequest], cloud_tpu.Node]: # In C++ this would require a dynamic_cast return self._GetNode(self._session, self._host, self._interceptor) # type: ignore + @property + def get_queued_resource( + self, + ) -> Callable[[cloud_tpu.GetQueuedResourceRequest], cloud_tpu.QueuedResource]: + # 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._GetQueuedResource(self._session, self._host, self._interceptor) # type: ignore + @property def get_runtime_version( self, @@ -2766,6 +3715,16 @@ def list_nodes( # In C++ this would require a dynamic_cast return self._ListNodes(self._session, self._host, self._interceptor) # type: ignore + @property + def list_queued_resources( + self, + ) -> Callable[ + [cloud_tpu.ListQueuedResourcesRequest], cloud_tpu.ListQueuedResourcesResponse + ]: + # 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._ListQueuedResources(self._session, self._host, self._interceptor) # type: ignore + @property def list_runtime_versions( self, @@ -2776,6 +3735,14 @@ def list_runtime_versions( # In C++ this would require a dynamic_cast return self._ListRuntimeVersions(self._session, self._host, self._interceptor) # type: ignore + @property + def reset_queued_resource( + self, + ) -> Callable[[cloud_tpu.ResetQueuedResourceRequest], 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._ResetQueuedResource(self._session, self._host, self._interceptor) # type: ignore + @property def start_node( self, diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/rest_base.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/rest_base.py index 5ccbfe4a45d0..b77366e6299d 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/rest_base.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/services/tpu/transports/rest_base.py @@ -146,6 +146,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseCreateQueuedResource: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/queuedResources", + "body": "queued_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_tpu.CreateQueuedResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTpuRestTransport._BaseCreateQueuedResource._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseDeleteNode: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -193,6 +250,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseDeleteQueuedResource: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/queuedResources/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_tpu.DeleteQueuedResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTpuRestTransport._BaseDeleteQueuedResource._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGenerateServiceIdentity: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -401,6 +505,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetQueuedResource: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/queuedResources/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_tpu.GetQueuedResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTpuRestTransport._BaseGetQueuedResource._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetRuntimeVersion: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -542,6 +693,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseListQueuedResources: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/queuedResources", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_tpu.ListQueuedResourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTpuRestTransport._BaseListQueuedResources._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseListRuntimeVersions: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -589,6 +787,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseResetQueuedResource: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/queuedResources/*}:reset", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_tpu.ResetQueuedResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTpuRestTransport._BaseResetQueuedResource._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseStartNode: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/types/__init__.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/types/__init__.py index 55f2ac4b2571..7e300f2e258a 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/types/__init__.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/types/__init__.py @@ -19,13 +19,16 @@ AccessConfig, AttachedDisk, CreateNodeRequest, + CreateQueuedResourceRequest, DeleteNodeRequest, + DeleteQueuedResourceRequest, GenerateServiceIdentityRequest, GenerateServiceIdentityResponse, GetAcceleratorTypeRequest, GetGuestAttributesRequest, GetGuestAttributesResponse, GetNodeRequest, + GetQueuedResourceRequest, GetRuntimeVersionRequest, GuestAttributes, GuestAttributesEntry, @@ -34,12 +37,17 @@ ListAcceleratorTypesResponse, ListNodesRequest, ListNodesResponse, + ListQueuedResourcesRequest, + ListQueuedResourcesResponse, ListRuntimeVersionsRequest, ListRuntimeVersionsResponse, NetworkConfig, NetworkEndpoint, Node, OperationMetadata, + QueuedResource, + QueuedResourceState, + ResetQueuedResourceRequest, RuntimeVersion, SchedulingConfig, ServiceAccount, @@ -57,13 +65,16 @@ "AccessConfig", "AttachedDisk", "CreateNodeRequest", + "CreateQueuedResourceRequest", "DeleteNodeRequest", + "DeleteQueuedResourceRequest", "GenerateServiceIdentityRequest", "GenerateServiceIdentityResponse", "GetAcceleratorTypeRequest", "GetGuestAttributesRequest", "GetGuestAttributesResponse", "GetNodeRequest", + "GetQueuedResourceRequest", "GetRuntimeVersionRequest", "GuestAttributes", "GuestAttributesEntry", @@ -72,12 +83,17 @@ "ListAcceleratorTypesResponse", "ListNodesRequest", "ListNodesResponse", + "ListQueuedResourcesRequest", + "ListQueuedResourcesResponse", "ListRuntimeVersionsRequest", "ListRuntimeVersionsResponse", "NetworkConfig", "NetworkEndpoint", "Node", "OperationMetadata", + "QueuedResource", + "QueuedResourceState", + "ResetQueuedResourceRequest", "RuntimeVersion", "SchedulingConfig", "ServiceAccount", diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/types/cloud_tpu.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/types/cloud_tpu.py index 658fc6f1e51c..23a86a3a1e73 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/types/cloud_tpu.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/types/cloud_tpu.py @@ -17,8 +17,11 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import interval_pb2 # type: ignore import proto # type: ignore __protobuf__ = proto.module( @@ -34,6 +37,8 @@ "NetworkConfig", "ServiceAccount", "Node", + "QueuedResource", + "QueuedResourceState", "ListNodesRequest", "ListNodesResponse", "GetNodeRequest", @@ -42,6 +47,12 @@ "StopNodeRequest", "StartNodeRequest", "UpdateNodeRequest", + "ListQueuedResourcesRequest", + "ListQueuedResourcesResponse", + "GetQueuedResourceRequest", + "CreateQueuedResourceRequest", + "DeleteQueuedResourceRequest", + "ResetQueuedResourceRequest", "ServiceIdentity", "GenerateServiceIdentityRequest", "GenerateServiceIdentityResponse", @@ -181,6 +192,9 @@ class SchedulingConfig(proto.Message): reserved (bool): Whether the node is created under a reservation. + spot (bool): + Optional. Defines whether the node is Spot + VM. """ preemptible: bool = proto.Field( @@ -191,6 +205,10 @@ class SchedulingConfig(proto.Message): proto.BOOL, number=2, ) + spot: bool = proto.Field( + proto.BOOL, + number=3, + ) class NetworkEndpoint(proto.Message): @@ -260,6 +278,9 @@ class NetworkConfig(proto.Message): packets with non-matching destination or source IPs. This is required if you plan to use the TPU workers to forward routes. + queue_count (int): + Optional. Specifies networking queue count + for TPU VM instance's network interface. """ network: str = proto.Field( @@ -278,6 +299,10 @@ class NetworkConfig(proto.Message): proto.BOOL, number=4, ) + queue_count: int = proto.Field( + proto.INT32, + number=6, + ) class ServiceAccount(proto.Message): @@ -327,7 +352,16 @@ class Node(proto.Message): Required. The runtime version running in the Node. network_config (google.cloud.tpu_v2.types.NetworkConfig): - Network configurations for the TPU node. + Network configurations for the TPU node. network_config and + network_configs are mutually exclusive, you can only specify + one of them. If both are specified, an error will be + returned. + network_configs (MutableSequence[google.cloud.tpu_v2.types.NetworkConfig]): + Optional. Repeated network configurations for the TPU node. + This field is used to specify multiple networks configs for + the TPU node. network_config and network_configs are + mutually exclusive, you can only specify one of them. If + both are specified, an error will be returned. cidr_block (str): The CIDR block that the TPU node will use when selecting an IP address. This CIDR block @@ -429,6 +463,9 @@ class State(proto.Enum): TPU node has been hidden. UNHIDING (15): TPU node is currently unhiding. + UNKNOWN (16): + TPU node has unknown state after a failed + repair. """ STATE_UNSPECIFIED = 0 CREATING = 1 @@ -445,6 +482,7 @@ class State(proto.Enum): HIDING = 13 HIDDEN = 14 UNHIDING = 15 + UNKNOWN = 16 class Health(proto.Enum): r"""Health defines the status of a TPU node as reported by @@ -522,6 +560,11 @@ class ApiVersion(proto.Enum): number=36, message="NetworkConfig", ) + network_configs: MutableSequence["NetworkConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=49, + message="NetworkConfig", + ) cidr_block: str = proto.Field( proto.STRING, number=13, @@ -604,6 +647,522 @@ class ApiVersion(proto.Enum): ) +class QueuedResource(proto.Message): + r"""A QueuedResource represents a request for resources that will + be placed in a queue and fulfilled when the necessary resources + are available. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Immutable. The name of the + QueuedResource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the QueuedResource + was created. + tpu (google.cloud.tpu_v2.types.QueuedResource.Tpu): + Optional. Defines a TPU resource. + + This field is a member of `oneof`_ ``resource``. + spot (google.cloud.tpu_v2.types.QueuedResource.Spot): + Optional. The Spot tier. + + This field is a member of `oneof`_ ``tier``. + guaranteed (google.cloud.tpu_v2.types.QueuedResource.Guaranteed): + Optional. The Guaranteed tier + + This field is a member of `oneof`_ ``tier``. + queueing_policy (google.cloud.tpu_v2.types.QueuedResource.QueueingPolicy): + Optional. The queueing policy of the + QueuedRequest. + state (google.cloud.tpu_v2.types.QueuedResourceState): + Output only. State of the QueuedResource + request. + reservation_name (str): + Optional. Name of the reservation in which + the resource should be provisioned. Format: + + projects/{project}/locations/{zone}/reservations/{reservation} + """ + + class Tpu(proto.Message): + r"""Details of the TPU resource(s) being requested. + + Attributes: + node_spec (MutableSequence[google.cloud.tpu_v2.types.QueuedResource.Tpu.NodeSpec]): + Optional. The TPU node(s) being requested. + """ + + class NodeSpec(proto.Message): + r"""Details of the TPU node(s) being requested. Users can request + either a single node or multiple nodes. + NodeSpec provides the specification for node(s) to be created. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent resource name. + node_id (str): + Optional. The unqualified resource name. Should follow the + ``^[A-Za-z0-9_.~+%-]+$`` regex format. This is only + specified when requesting a single node. In case of + multislice requests, multislice_params must be populated + instead. + + This field is a member of `oneof`_ ``name_strategy``. + multislice_params (google.cloud.tpu_v2.types.QueuedResource.Tpu.NodeSpec.MultisliceParams): + Optional. Fields to specify in case of + multislice request. + + This field is a member of `oneof`_ ``name_strategy``. + node (google.cloud.tpu_v2.types.Node): + Required. The node. + """ + + class MultisliceParams(proto.Message): + r"""Parameters to specify for multislice QueuedResource requests. This + message must be populated in case of multislice requests instead of + node_id. + + Attributes: + node_count (int): + Required. Number of nodes with this spec. The system will + attempt to provision "node_count" nodes as part of the + request. This needs to be > 1. + node_id_prefix (str): + Optional. Prefix of node_ids in case of multislice request. + Should follow the ``^[A-Za-z0-9_.~+%-]+$`` regex format. If + node_count = 3 and node_id_prefix = "np", node ids of nodes + created will be "np-0", "np-1", "np-2". If this field is not + provided we use queued_resource_id as the node_id_prefix. + """ + + node_count: int = proto.Field( + proto.INT32, + number=1, + ) + node_id_prefix: str = proto.Field( + proto.STRING, + number=2, + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + node_id: str = proto.Field( + proto.STRING, + number=2, + oneof="name_strategy", + ) + multislice_params: "QueuedResource.Tpu.NodeSpec.MultisliceParams" = ( + proto.Field( + proto.MESSAGE, + number=3, + oneof="name_strategy", + message="QueuedResource.Tpu.NodeSpec.MultisliceParams", + ) + ) + node: "Node" = proto.Field( + proto.MESSAGE, + number=4, + message="Node", + ) + + node_spec: MutableSequence["QueuedResource.Tpu.NodeSpec"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="QueuedResource.Tpu.NodeSpec", + ) + + class Spot(proto.Message): + r"""Spot tier definition.""" + + class Guaranteed(proto.Message): + r"""Guaranteed tier definition. + + Attributes: + min_duration (google.protobuf.duration_pb2.Duration): + Optional. Defines the minimum duration of the + guarantee. If specified, the requested resources + will only be provisioned if they can be + allocated for at least the given duration. + """ + + min_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + class QueueingPolicy(proto.Message): + r"""Defines the policy of the QueuedRequest. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + valid_until_duration (google.protobuf.duration_pb2.Duration): + Optional. A relative time after which + resources should not be created. If the request + cannot be fulfilled by this time the request + will be failed. + + This field is a member of `oneof`_ ``start_timing_constraints``. + valid_until_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. An absolute time after which + resources should not be created. If the request + cannot be fulfilled by this time the request + will be failed. + + This field is a member of `oneof`_ ``start_timing_constraints``. + valid_after_duration (google.protobuf.duration_pb2.Duration): + Optional. A relative time after which + resources may be created. + + This field is a member of `oneof`_ ``start_timing_constraints``. + valid_after_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. An absolute time after which + resources may be created. + + This field is a member of `oneof`_ ``start_timing_constraints``. + valid_interval (google.type.interval_pb2.Interval): + Optional. An absolute time interval within + which resources may be created. + + This field is a member of `oneof`_ ``start_timing_constraints``. + """ + + valid_until_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + oneof="start_timing_constraints", + message=duration_pb2.Duration, + ) + valid_until_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + oneof="start_timing_constraints", + message=timestamp_pb2.Timestamp, + ) + valid_after_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + oneof="start_timing_constraints", + message=duration_pb2.Duration, + ) + valid_after_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + oneof="start_timing_constraints", + message=timestamp_pb2.Timestamp, + ) + valid_interval: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=5, + oneof="start_timing_constraints", + message=interval_pb2.Interval, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + tpu: Tpu = proto.Field( + proto.MESSAGE, + number=2, + oneof="resource", + message=Tpu, + ) + spot: Spot = proto.Field( + proto.MESSAGE, + number=3, + oneof="tier", + message=Spot, + ) + guaranteed: Guaranteed = proto.Field( + proto.MESSAGE, + number=4, + oneof="tier", + message=Guaranteed, + ) + queueing_policy: QueueingPolicy = proto.Field( + proto.MESSAGE, + number=5, + message=QueueingPolicy, + ) + state: "QueuedResourceState" = proto.Field( + proto.MESSAGE, + number=6, + message="QueuedResourceState", + ) + reservation_name: str = proto.Field( + proto.STRING, + number=7, + ) + + +class QueuedResourceState(proto.Message): + r"""QueuedResourceState defines the details of the QueuedResource + request. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + state (google.cloud.tpu_v2.types.QueuedResourceState.State): + Output only. State of the QueuedResource + request. + creating_data (google.cloud.tpu_v2.types.QueuedResourceState.CreatingData): + Output only. Further data for the creating + state. + + This field is a member of `oneof`_ ``state_data``. + accepted_data (google.cloud.tpu_v2.types.QueuedResourceState.AcceptedData): + Output only. Further data for the accepted + state. + + This field is a member of `oneof`_ ``state_data``. + provisioning_data (google.cloud.tpu_v2.types.QueuedResourceState.ProvisioningData): + Output only. Further data for the + provisioning state. + + This field is a member of `oneof`_ ``state_data``. + failed_data (google.cloud.tpu_v2.types.QueuedResourceState.FailedData): + Output only. Further data for the failed + state. + + This field is a member of `oneof`_ ``state_data``. + deleting_data (google.cloud.tpu_v2.types.QueuedResourceState.DeletingData): + Output only. Further data for the deleting + state. + + This field is a member of `oneof`_ ``state_data``. + active_data (google.cloud.tpu_v2.types.QueuedResourceState.ActiveData): + Output only. Further data for the active + state. + + This field is a member of `oneof`_ ``state_data``. + suspending_data (google.cloud.tpu_v2.types.QueuedResourceState.SuspendingData): + Output only. Further data for the suspending + state. + + This field is a member of `oneof`_ ``state_data``. + suspended_data (google.cloud.tpu_v2.types.QueuedResourceState.SuspendedData): + Output only. Further data for the suspended + state. + + This field is a member of `oneof`_ ``state_data``. + state_initiator (google.cloud.tpu_v2.types.QueuedResourceState.StateInitiator): + Output only. The initiator of the + QueuedResources's current state. Used to + indicate whether the SUSPENDING/SUSPENDED state + was initiated by the user or the service. + """ + + class State(proto.Enum): + r"""Output only state of the request + + Values: + STATE_UNSPECIFIED (0): + State of the QueuedResource request is not + known/set. + CREATING (1): + The QueuedResource request has been received. + We're still working on determining if we will be + able to honor this request. + ACCEPTED (2): + The QueuedResource request has passed initial + validation/admission control and has been + persisted in the queue. + PROVISIONING (3): + The QueuedResource request has been selected. + The associated resources are currently being + provisioned (or very soon will begin + provisioning). + FAILED (4): + The request could not be completed. This may + be due to some late-discovered problem with the + request itself, or due to unavailability of + resources within the constraints of the request + (e.g., the 'valid until' start timing constraint + expired). + DELETING (5): + The QueuedResource is being deleted. + ACTIVE (6): + The resources specified in the QueuedResource + request have been provisioned and are ready for + use by the end-user/consumer. + SUSPENDING (7): + The resources specified in the QueuedResource + request are being deleted. This may have been + initiated by the user, or the Cloud TPU service. + Inspect the state data for more details. + SUSPENDED (8): + The resources specified in the QueuedResource + request have been deleted. + WAITING_FOR_RESOURCES (9): + The QueuedResource request has passed initial validation and + has been persisted in the queue. It will remain in this + state until there are sufficient free resources to begin + provisioning your request. Wait times will vary + significantly depending on demand levels. When demand is + high, not all requests can be immediately provisioned. If + you need more reliable obtainability of TPUs consider + purchasing a reservation. To put a limit on how long you are + willing to wait, use `timing + constraints `__. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACCEPTED = 2 + PROVISIONING = 3 + FAILED = 4 + DELETING = 5 + ACTIVE = 6 + SUSPENDING = 7 + SUSPENDED = 8 + WAITING_FOR_RESOURCES = 9 + + class StateInitiator(proto.Enum): + r"""The initiator of the QueuedResource's SUSPENDING/SUSPENDED + state. + + Values: + STATE_INITIATOR_UNSPECIFIED (0): + The state initiator is unspecified. + USER (1): + The current QueuedResource state was + initiated by the user. + SERVICE (2): + The current QueuedResource state was + initiated by the service. + """ + STATE_INITIATOR_UNSPECIFIED = 0 + USER = 1 + SERVICE = 2 + + class CreatingData(proto.Message): + r"""Further data for the creating state.""" + + class AcceptedData(proto.Message): + r"""Further data for the accepted state.""" + + class ProvisioningData(proto.Message): + r"""Further data for the provisioning state.""" + + class FailedData(proto.Message): + r"""Further data for the failed state. + + Attributes: + error (google.rpc.status_pb2.Status): + Output only. The error that caused the queued + resource to enter the FAILED state. + """ + + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + class DeletingData(proto.Message): + r"""Further data for the deleting state.""" + + class ActiveData(proto.Message): + r"""Further data for the active state.""" + + class SuspendingData(proto.Message): + r"""Further data for the suspending state.""" + + class SuspendedData(proto.Message): + r"""Further data for the suspended state.""" + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + creating_data: CreatingData = proto.Field( + proto.MESSAGE, + number=2, + oneof="state_data", + message=CreatingData, + ) + accepted_data: AcceptedData = proto.Field( + proto.MESSAGE, + number=3, + oneof="state_data", + message=AcceptedData, + ) + provisioning_data: ProvisioningData = proto.Field( + proto.MESSAGE, + number=4, + oneof="state_data", + message=ProvisioningData, + ) + failed_data: FailedData = proto.Field( + proto.MESSAGE, + number=5, + oneof="state_data", + message=FailedData, + ) + deleting_data: DeletingData = proto.Field( + proto.MESSAGE, + number=6, + oneof="state_data", + message=DeletingData, + ) + active_data: ActiveData = proto.Field( + proto.MESSAGE, + number=7, + oneof="state_data", + message=ActiveData, + ) + suspending_data: SuspendingData = proto.Field( + proto.MESSAGE, + number=8, + oneof="state_data", + message=SuspendingData, + ) + suspended_data: SuspendedData = proto.Field( + proto.MESSAGE, + number=9, + oneof="state_data", + message=SuspendedData, + ) + state_initiator: StateInitiator = proto.Field( + proto.ENUM, + number=10, + enum=StateInitiator, + ) + + class ListNodesRequest(proto.Message): r"""Request for [ListNodes][google.cloud.tpu.v2.Tpu.ListNodes]. @@ -770,6 +1329,166 @@ class UpdateNodeRequest(proto.Message): ) +class ListQueuedResourcesRequest(proto.Message): + r"""Request for + [ListQueuedResources][google.cloud.tpu.v2.Tpu.ListQueuedResources]. + + Attributes: + parent (str): + Required. The parent resource name. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListQueuedResourcesResponse(proto.Message): + r"""Response for + [ListQueuedResources][google.cloud.tpu.v2.Tpu.ListQueuedResources]. + + Attributes: + queued_resources (MutableSequence[google.cloud.tpu_v2.types.QueuedResource]): + The listed queued resources. + next_page_token (str): + The next page token or empty if none. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + queued_resources: MutableSequence["QueuedResource"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="QueuedResource", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetQueuedResourceRequest(proto.Message): + r"""Request for + [GetQueuedResource][google.cloud.tpu.v2.Tpu.GetQueuedResource] + + Attributes: + name (str): + Required. The resource name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateQueuedResourceRequest(proto.Message): + r"""Request for + [CreateQueuedResource][google.cloud.tpu.v2.Tpu.CreateQueuedResource]. + + Attributes: + parent (str): + Required. The parent resource name. + queued_resource_id (str): + Optional. The unqualified resource name. Should follow the + ``^[A-Za-z0-9_.~+%-]+$`` regex format. + queued_resource (google.cloud.tpu_v2.types.QueuedResource): + Required. The queued resource. + request_id (str): + Optional. Idempotent request UUID. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + queued_resource_id: str = proto.Field( + proto.STRING, + number=2, + ) + queued_resource: "QueuedResource" = proto.Field( + proto.MESSAGE, + number=3, + message="QueuedResource", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteQueuedResourceRequest(proto.Message): + r"""Request for + [DeleteQueuedResource][google.cloud.tpu.v2.Tpu.DeleteQueuedResource]. + + Attributes: + name (str): + Required. The resource name. + request_id (str): + Optional. Idempotent request UUID. + force (bool): + Optional. If set to true, all running nodes + belonging to this queued resource will be + deleted first and then the queued resource will + be deleted. Otherwise (i.e. force=false), the + queued resource will only be deleted if its + nodes have already been deleted or the queued + resource is in the ACCEPTED, FAILED, or + SUSPENDED state. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ResetQueuedResourceRequest(proto.Message): + r"""Request for + [ResetQueuedResource][google.cloud.tpu.v2.Tpu.ResetQueuedResource]. + + Attributes: + name (str): + Required. The name of the queued resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class ServiceIdentity(proto.Message): r"""The per-product per-project service identity for Cloud TPU service. @@ -1224,11 +1943,20 @@ class Type(proto.Enum): TPU v3. V4 (7): TPU v4. + V5LITE_POD (9): + TPU v5lite pod. + V5P (10): + TPU v5p. + V6E (11): + TPU v6e. """ TYPE_UNSPECIFIED = 0 V2 = 2 V3 = 4 V4 = 7 + V5LITE_POD = 9 + V5P = 10 + V6E = 11 type_: Type = proto.Field( proto.ENUM, diff --git a/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2.json b/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2.json index f887178885e7..bca59a74df6e 100644 --- a/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2.json +++ b/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2.json @@ -188,6 +188,183 @@ ], "title": "tpu_v2_generated_tpu_create_node_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.tpu_v2.TpuAsyncClient", + "shortName": "TpuAsyncClient" + }, + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.create_queued_resource", + "method": { + "fullName": "google.cloud.tpu.v2.Tpu.CreateQueuedResource", + "service": { + "fullName": "google.cloud.tpu.v2.Tpu", + "shortName": "Tpu" + }, + "shortName": "CreateQueuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.tpu_v2.types.CreateQueuedResourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "queued_resource", + "type": "google.cloud.tpu_v2.types.QueuedResource" + }, + { + "name": "queued_resource_id", + "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": "create_queued_resource" + }, + "description": "Sample for CreateQueuedResource", + "file": "tpu_v2_generated_tpu_create_queued_resource_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "tpu_v2_generated_Tpu_CreateQueuedResource_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": "tpu_v2_generated_tpu_create_queued_resource_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.tpu_v2.TpuClient", + "shortName": "TpuClient" + }, + "fullName": "google.cloud.tpu_v2.TpuClient.create_queued_resource", + "method": { + "fullName": "google.cloud.tpu.v2.Tpu.CreateQueuedResource", + "service": { + "fullName": "google.cloud.tpu.v2.Tpu", + "shortName": "Tpu" + }, + "shortName": "CreateQueuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.tpu_v2.types.CreateQueuedResourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "queued_resource", + "type": "google.cloud.tpu_v2.types.QueuedResource" + }, + { + "name": "queued_resource_id", + "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": "create_queued_resource" + }, + "description": "Sample for CreateQueuedResource", + "file": "tpu_v2_generated_tpu_create_queued_resource_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "tpu_v2_generated_Tpu_CreateQueuedResource_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": "tpu_v2_generated_tpu_create_queued_resource_sync.py" + }, { "canonical": true, "clientMethod": { @@ -357,19 +534,23 @@ "fullName": "google.cloud.tpu_v2.TpuAsyncClient", "shortName": "TpuAsyncClient" }, - "fullName": "google.cloud.tpu_v2.TpuAsyncClient.generate_service_identity", + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.delete_queued_resource", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.GenerateServiceIdentity", + "fullName": "google.cloud.tpu.v2.Tpu.DeleteQueuedResource", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "GenerateServiceIdentity" + "shortName": "DeleteQueuedResource" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.GenerateServiceIdentityRequest" + "type": "google.cloud.tpu_v2.types.DeleteQueuedResourceRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -384,22 +565,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.types.GenerateServiceIdentityResponse", - "shortName": "generate_service_identity" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_queued_resource" }, - "description": "Sample for GenerateServiceIdentity", - "file": "tpu_v2_generated_tpu_generate_service_identity_async.py", + "description": "Sample for DeleteQueuedResource", + "file": "tpu_v2_generated_tpu_delete_queued_resource_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_GenerateServiceIdentity_async", + "regionTag": "tpu_v2_generated_Tpu_DeleteQueuedResource_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -414,17 +595,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_generate_service_identity_async.py" + "title": "tpu_v2_generated_tpu_delete_queued_resource_async.py" }, { "canonical": true, @@ -433,19 +614,23 @@ "fullName": "google.cloud.tpu_v2.TpuClient", "shortName": "TpuClient" }, - "fullName": "google.cloud.tpu_v2.TpuClient.generate_service_identity", + "fullName": "google.cloud.tpu_v2.TpuClient.delete_queued_resource", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.GenerateServiceIdentity", + "fullName": "google.cloud.tpu.v2.Tpu.DeleteQueuedResource", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "GenerateServiceIdentity" + "shortName": "DeleteQueuedResource" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.GenerateServiceIdentityRequest" + "type": "google.cloud.tpu_v2.types.DeleteQueuedResourceRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -460,22 +645,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.types.GenerateServiceIdentityResponse", - "shortName": "generate_service_identity" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_queued_resource" }, - "description": "Sample for GenerateServiceIdentity", - "file": "tpu_v2_generated_tpu_generate_service_identity_sync.py", + "description": "Sample for DeleteQueuedResource", + "file": "tpu_v2_generated_tpu_delete_queued_resource_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_GenerateServiceIdentity_sync", + "regionTag": "tpu_v2_generated_Tpu_DeleteQueuedResource_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -490,17 +675,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_generate_service_identity_sync.py" + "title": "tpu_v2_generated_tpu_delete_queued_resource_sync.py" }, { "canonical": true, @@ -510,23 +695,19 @@ "fullName": "google.cloud.tpu_v2.TpuAsyncClient", "shortName": "TpuAsyncClient" }, - "fullName": "google.cloud.tpu_v2.TpuAsyncClient.get_accelerator_type", + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.generate_service_identity", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.GetAcceleratorType", + "fullName": "google.cloud.tpu.v2.Tpu.GenerateServiceIdentity", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "GetAcceleratorType" + "shortName": "GenerateServiceIdentity" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.GetAcceleratorTypeRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.tpu_v2.types.GenerateServiceIdentityRequest" }, { "name": "retry", @@ -541,14 +722,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.types.AcceleratorType", - "shortName": "get_accelerator_type" + "resultType": "google.cloud.tpu_v2.types.GenerateServiceIdentityResponse", + "shortName": "generate_service_identity" }, - "description": "Sample for GetAcceleratorType", - "file": "tpu_v2_generated_tpu_get_accelerator_type_async.py", + "description": "Sample for GenerateServiceIdentity", + "file": "tpu_v2_generated_tpu_generate_service_identity_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_GetAcceleratorType_async", + "regionTag": "tpu_v2_generated_Tpu_GenerateServiceIdentity_async", "segments": [ { "end": 51, @@ -581,7 +762,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_get_accelerator_type_async.py" + "title": "tpu_v2_generated_tpu_generate_service_identity_async.py" }, { "canonical": true, @@ -590,23 +771,19 @@ "fullName": "google.cloud.tpu_v2.TpuClient", "shortName": "TpuClient" }, - "fullName": "google.cloud.tpu_v2.TpuClient.get_accelerator_type", + "fullName": "google.cloud.tpu_v2.TpuClient.generate_service_identity", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.GetAcceleratorType", + "fullName": "google.cloud.tpu.v2.Tpu.GenerateServiceIdentity", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "GetAcceleratorType" + "shortName": "GenerateServiceIdentity" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.GetAcceleratorTypeRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.tpu_v2.types.GenerateServiceIdentityRequest" }, { "name": "retry", @@ -621,14 +798,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.types.AcceleratorType", - "shortName": "get_accelerator_type" + "resultType": "google.cloud.tpu_v2.types.GenerateServiceIdentityResponse", + "shortName": "generate_service_identity" }, - "description": "Sample for GetAcceleratorType", - "file": "tpu_v2_generated_tpu_get_accelerator_type_sync.py", + "description": "Sample for GenerateServiceIdentity", + "file": "tpu_v2_generated_tpu_generate_service_identity_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_GetAcceleratorType_sync", + "regionTag": "tpu_v2_generated_Tpu_GenerateServiceIdentity_sync", "segments": [ { "end": 51, @@ -661,7 +838,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_get_accelerator_type_sync.py" + "title": "tpu_v2_generated_tpu_generate_service_identity_sync.py" }, { "canonical": true, @@ -671,14 +848,251 @@ "fullName": "google.cloud.tpu_v2.TpuAsyncClient", "shortName": "TpuAsyncClient" }, - "fullName": "google.cloud.tpu_v2.TpuAsyncClient.get_guest_attributes", + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.get_accelerator_type", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.GetGuestAttributes", + "fullName": "google.cloud.tpu.v2.Tpu.GetAcceleratorType", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "GetGuestAttributes" + "shortName": "GetAcceleratorType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.tpu_v2.types.GetAcceleratorTypeRequest" + }, + { + "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.tpu_v2.types.AcceleratorType", + "shortName": "get_accelerator_type" + }, + "description": "Sample for GetAcceleratorType", + "file": "tpu_v2_generated_tpu_get_accelerator_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "tpu_v2_generated_Tpu_GetAcceleratorType_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": "tpu_v2_generated_tpu_get_accelerator_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.tpu_v2.TpuClient", + "shortName": "TpuClient" + }, + "fullName": "google.cloud.tpu_v2.TpuClient.get_accelerator_type", + "method": { + "fullName": "google.cloud.tpu.v2.Tpu.GetAcceleratorType", + "service": { + "fullName": "google.cloud.tpu.v2.Tpu", + "shortName": "Tpu" + }, + "shortName": "GetAcceleratorType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.tpu_v2.types.GetAcceleratorTypeRequest" + }, + { + "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.tpu_v2.types.AcceleratorType", + "shortName": "get_accelerator_type" + }, + "description": "Sample for GetAcceleratorType", + "file": "tpu_v2_generated_tpu_get_accelerator_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "tpu_v2_generated_Tpu_GetAcceleratorType_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": "tpu_v2_generated_tpu_get_accelerator_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.tpu_v2.TpuAsyncClient", + "shortName": "TpuAsyncClient" + }, + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.get_guest_attributes", + "method": { + "fullName": "google.cloud.tpu.v2.Tpu.GetGuestAttributes", + "service": { + "fullName": "google.cloud.tpu.v2.Tpu", + "shortName": "Tpu" + }, + "shortName": "GetGuestAttributes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.tpu_v2.types.GetGuestAttributesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.tpu_v2.types.GetGuestAttributesResponse", + "shortName": "get_guest_attributes" + }, + "description": "Sample for GetGuestAttributes", + "file": "tpu_v2_generated_tpu_get_guest_attributes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "tpu_v2_generated_Tpu_GetGuestAttributes_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": "tpu_v2_generated_tpu_get_guest_attributes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.tpu_v2.TpuClient", + "shortName": "TpuClient" + }, + "fullName": "google.cloud.tpu_v2.TpuClient.get_guest_attributes", + "method": { + "fullName": "google.cloud.tpu.v2.Tpu.GetGuestAttributes", + "service": { + "fullName": "google.cloud.tpu.v2.Tpu", + "shortName": "Tpu" + }, + "shortName": "GetGuestAttributes" }, "parameters": [ { @@ -698,14 +1112,417 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.types.GetGuestAttributesResponse", - "shortName": "get_guest_attributes" + "resultType": "google.cloud.tpu_v2.types.GetGuestAttributesResponse", + "shortName": "get_guest_attributes" + }, + "description": "Sample for GetGuestAttributes", + "file": "tpu_v2_generated_tpu_get_guest_attributes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "tpu_v2_generated_Tpu_GetGuestAttributes_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": "tpu_v2_generated_tpu_get_guest_attributes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.tpu_v2.TpuAsyncClient", + "shortName": "TpuAsyncClient" + }, + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.get_node", + "method": { + "fullName": "google.cloud.tpu.v2.Tpu.GetNode", + "service": { + "fullName": "google.cloud.tpu.v2.Tpu", + "shortName": "Tpu" + }, + "shortName": "GetNode" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.tpu_v2.types.GetNodeRequest" + }, + { + "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.tpu_v2.types.Node", + "shortName": "get_node" + }, + "description": "Sample for GetNode", + "file": "tpu_v2_generated_tpu_get_node_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "tpu_v2_generated_Tpu_GetNode_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": "tpu_v2_generated_tpu_get_node_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.tpu_v2.TpuClient", + "shortName": "TpuClient" + }, + "fullName": "google.cloud.tpu_v2.TpuClient.get_node", + "method": { + "fullName": "google.cloud.tpu.v2.Tpu.GetNode", + "service": { + "fullName": "google.cloud.tpu.v2.Tpu", + "shortName": "Tpu" + }, + "shortName": "GetNode" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.tpu_v2.types.GetNodeRequest" + }, + { + "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.tpu_v2.types.Node", + "shortName": "get_node" + }, + "description": "Sample for GetNode", + "file": "tpu_v2_generated_tpu_get_node_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "tpu_v2_generated_Tpu_GetNode_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": "tpu_v2_generated_tpu_get_node_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.tpu_v2.TpuAsyncClient", + "shortName": "TpuAsyncClient" + }, + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.get_queued_resource", + "method": { + "fullName": "google.cloud.tpu.v2.Tpu.GetQueuedResource", + "service": { + "fullName": "google.cloud.tpu.v2.Tpu", + "shortName": "Tpu" + }, + "shortName": "GetQueuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.tpu_v2.types.GetQueuedResourceRequest" + }, + { + "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.tpu_v2.types.QueuedResource", + "shortName": "get_queued_resource" + }, + "description": "Sample for GetQueuedResource", + "file": "tpu_v2_generated_tpu_get_queued_resource_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "tpu_v2_generated_Tpu_GetQueuedResource_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": "tpu_v2_generated_tpu_get_queued_resource_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.tpu_v2.TpuClient", + "shortName": "TpuClient" + }, + "fullName": "google.cloud.tpu_v2.TpuClient.get_queued_resource", + "method": { + "fullName": "google.cloud.tpu.v2.Tpu.GetQueuedResource", + "service": { + "fullName": "google.cloud.tpu.v2.Tpu", + "shortName": "Tpu" + }, + "shortName": "GetQueuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.tpu_v2.types.GetQueuedResourceRequest" + }, + { + "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.tpu_v2.types.QueuedResource", + "shortName": "get_queued_resource" + }, + "description": "Sample for GetQueuedResource", + "file": "tpu_v2_generated_tpu_get_queued_resource_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "tpu_v2_generated_Tpu_GetQueuedResource_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": "tpu_v2_generated_tpu_get_queued_resource_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.tpu_v2.TpuAsyncClient", + "shortName": "TpuAsyncClient" + }, + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.get_runtime_version", + "method": { + "fullName": "google.cloud.tpu.v2.Tpu.GetRuntimeVersion", + "service": { + "fullName": "google.cloud.tpu.v2.Tpu", + "shortName": "Tpu" + }, + "shortName": "GetRuntimeVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.tpu_v2.types.GetRuntimeVersionRequest" + }, + { + "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.tpu_v2.types.RuntimeVersion", + "shortName": "get_runtime_version" }, - "description": "Sample for GetGuestAttributes", - "file": "tpu_v2_generated_tpu_get_guest_attributes_async.py", + "description": "Sample for GetRuntimeVersion", + "file": "tpu_v2_generated_tpu_get_runtime_version_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_GetGuestAttributes_async", + "regionTag": "tpu_v2_generated_Tpu_GetRuntimeVersion_async", "segments": [ { "end": 51, @@ -738,7 +1555,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_get_guest_attributes_async.py" + "title": "tpu_v2_generated_tpu_get_runtime_version_async.py" }, { "canonical": true, @@ -747,19 +1564,23 @@ "fullName": "google.cloud.tpu_v2.TpuClient", "shortName": "TpuClient" }, - "fullName": "google.cloud.tpu_v2.TpuClient.get_guest_attributes", + "fullName": "google.cloud.tpu_v2.TpuClient.get_runtime_version", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.GetGuestAttributes", + "fullName": "google.cloud.tpu.v2.Tpu.GetRuntimeVersion", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "GetGuestAttributes" + "shortName": "GetRuntimeVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.GetGuestAttributesRequest" + "type": "google.cloud.tpu_v2.types.GetRuntimeVersionRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -774,14 +1595,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.types.GetGuestAttributesResponse", - "shortName": "get_guest_attributes" + "resultType": "google.cloud.tpu_v2.types.RuntimeVersion", + "shortName": "get_runtime_version" }, - "description": "Sample for GetGuestAttributes", - "file": "tpu_v2_generated_tpu_get_guest_attributes_sync.py", + "description": "Sample for GetRuntimeVersion", + "file": "tpu_v2_generated_tpu_get_runtime_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_GetGuestAttributes_sync", + "regionTag": "tpu_v2_generated_Tpu_GetRuntimeVersion_sync", "segments": [ { "end": 51, @@ -814,7 +1635,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_get_guest_attributes_sync.py" + "title": "tpu_v2_generated_tpu_get_runtime_version_sync.py" }, { "canonical": true, @@ -824,22 +1645,22 @@ "fullName": "google.cloud.tpu_v2.TpuAsyncClient", "shortName": "TpuAsyncClient" }, - "fullName": "google.cloud.tpu_v2.TpuAsyncClient.get_node", + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.list_accelerator_types", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.GetNode", + "fullName": "google.cloud.tpu.v2.Tpu.ListAcceleratorTypes", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "GetNode" + "shortName": "ListAcceleratorTypes" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.GetNodeRequest" + "type": "google.cloud.tpu_v2.types.ListAcceleratorTypesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -855,22 +1676,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.types.Node", - "shortName": "get_node" + "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListAcceleratorTypesAsyncPager", + "shortName": "list_accelerator_types" }, - "description": "Sample for GetNode", - "file": "tpu_v2_generated_tpu_get_node_async.py", + "description": "Sample for ListAcceleratorTypes", + "file": "tpu_v2_generated_tpu_list_accelerator_types_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_GetNode_async", + "regionTag": "tpu_v2_generated_Tpu_ListAcceleratorTypes_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -890,12 +1711,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_get_node_async.py" + "title": "tpu_v2_generated_tpu_list_accelerator_types_async.py" }, { "canonical": true, @@ -904,22 +1725,22 @@ "fullName": "google.cloud.tpu_v2.TpuClient", "shortName": "TpuClient" }, - "fullName": "google.cloud.tpu_v2.TpuClient.get_node", + "fullName": "google.cloud.tpu_v2.TpuClient.list_accelerator_types", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.GetNode", + "fullName": "google.cloud.tpu.v2.Tpu.ListAcceleratorTypes", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "GetNode" + "shortName": "ListAcceleratorTypes" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.GetNodeRequest" + "type": "google.cloud.tpu_v2.types.ListAcceleratorTypesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -935,22 +1756,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.types.Node", - "shortName": "get_node" + "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListAcceleratorTypesPager", + "shortName": "list_accelerator_types" }, - "description": "Sample for GetNode", - "file": "tpu_v2_generated_tpu_get_node_sync.py", + "description": "Sample for ListAcceleratorTypes", + "file": "tpu_v2_generated_tpu_list_accelerator_types_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_GetNode_sync", + "regionTag": "tpu_v2_generated_Tpu_ListAcceleratorTypes_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -970,12 +1791,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_get_node_sync.py" + "title": "tpu_v2_generated_tpu_list_accelerator_types_sync.py" }, { "canonical": true, @@ -985,22 +1806,22 @@ "fullName": "google.cloud.tpu_v2.TpuAsyncClient", "shortName": "TpuAsyncClient" }, - "fullName": "google.cloud.tpu_v2.TpuAsyncClient.get_runtime_version", + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.list_nodes", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.GetRuntimeVersion", + "fullName": "google.cloud.tpu.v2.Tpu.ListNodes", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "GetRuntimeVersion" + "shortName": "ListNodes" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.GetRuntimeVersionRequest" + "type": "google.cloud.tpu_v2.types.ListNodesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -1016,22 +1837,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.types.RuntimeVersion", - "shortName": "get_runtime_version" + "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListNodesAsyncPager", + "shortName": "list_nodes" }, - "description": "Sample for GetRuntimeVersion", - "file": "tpu_v2_generated_tpu_get_runtime_version_async.py", + "description": "Sample for ListNodes", + "file": "tpu_v2_generated_tpu_list_nodes_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_GetRuntimeVersion_async", + "regionTag": "tpu_v2_generated_Tpu_ListNodes_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1051,12 +1872,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_get_runtime_version_async.py" + "title": "tpu_v2_generated_tpu_list_nodes_async.py" }, { "canonical": true, @@ -1065,22 +1886,22 @@ "fullName": "google.cloud.tpu_v2.TpuClient", "shortName": "TpuClient" }, - "fullName": "google.cloud.tpu_v2.TpuClient.get_runtime_version", + "fullName": "google.cloud.tpu_v2.TpuClient.list_nodes", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.GetRuntimeVersion", + "fullName": "google.cloud.tpu.v2.Tpu.ListNodes", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "GetRuntimeVersion" + "shortName": "ListNodes" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.GetRuntimeVersionRequest" + "type": "google.cloud.tpu_v2.types.ListNodesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -1096,22 +1917,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.types.RuntimeVersion", - "shortName": "get_runtime_version" + "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListNodesPager", + "shortName": "list_nodes" }, - "description": "Sample for GetRuntimeVersion", - "file": "tpu_v2_generated_tpu_get_runtime_version_sync.py", + "description": "Sample for ListNodes", + "file": "tpu_v2_generated_tpu_list_nodes_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_GetRuntimeVersion_sync", + "regionTag": "tpu_v2_generated_Tpu_ListNodes_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1131,12 +1952,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_get_runtime_version_sync.py" + "title": "tpu_v2_generated_tpu_list_nodes_sync.py" }, { "canonical": true, @@ -1146,19 +1967,19 @@ "fullName": "google.cloud.tpu_v2.TpuAsyncClient", "shortName": "TpuAsyncClient" }, - "fullName": "google.cloud.tpu_v2.TpuAsyncClient.list_accelerator_types", + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.list_queued_resources", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.ListAcceleratorTypes", + "fullName": "google.cloud.tpu.v2.Tpu.ListQueuedResources", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "ListAcceleratorTypes" + "shortName": "ListQueuedResources" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.ListAcceleratorTypesRequest" + "type": "google.cloud.tpu_v2.types.ListQueuedResourcesRequest" }, { "name": "parent", @@ -1177,14 +1998,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListAcceleratorTypesAsyncPager", - "shortName": "list_accelerator_types" + "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListQueuedResourcesAsyncPager", + "shortName": "list_queued_resources" }, - "description": "Sample for ListAcceleratorTypes", - "file": "tpu_v2_generated_tpu_list_accelerator_types_async.py", + "description": "Sample for ListQueuedResources", + "file": "tpu_v2_generated_tpu_list_queued_resources_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_ListAcceleratorTypes_async", + "regionTag": "tpu_v2_generated_Tpu_ListQueuedResources_async", "segments": [ { "end": 52, @@ -1217,7 +2038,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_list_accelerator_types_async.py" + "title": "tpu_v2_generated_tpu_list_queued_resources_async.py" }, { "canonical": true, @@ -1226,19 +2047,19 @@ "fullName": "google.cloud.tpu_v2.TpuClient", "shortName": "TpuClient" }, - "fullName": "google.cloud.tpu_v2.TpuClient.list_accelerator_types", + "fullName": "google.cloud.tpu_v2.TpuClient.list_queued_resources", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.ListAcceleratorTypes", + "fullName": "google.cloud.tpu.v2.Tpu.ListQueuedResources", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "ListAcceleratorTypes" + "shortName": "ListQueuedResources" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.ListAcceleratorTypesRequest" + "type": "google.cloud.tpu_v2.types.ListQueuedResourcesRequest" }, { "name": "parent", @@ -1257,14 +2078,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListAcceleratorTypesPager", - "shortName": "list_accelerator_types" + "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListQueuedResourcesPager", + "shortName": "list_queued_resources" }, - "description": "Sample for ListAcceleratorTypes", - "file": "tpu_v2_generated_tpu_list_accelerator_types_sync.py", + "description": "Sample for ListQueuedResources", + "file": "tpu_v2_generated_tpu_list_queued_resources_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_ListAcceleratorTypes_sync", + "regionTag": "tpu_v2_generated_Tpu_ListQueuedResources_sync", "segments": [ { "end": 52, @@ -1297,7 +2118,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_list_accelerator_types_sync.py" + "title": "tpu_v2_generated_tpu_list_queued_resources_sync.py" }, { "canonical": true, @@ -1307,19 +2128,19 @@ "fullName": "google.cloud.tpu_v2.TpuAsyncClient", "shortName": "TpuAsyncClient" }, - "fullName": "google.cloud.tpu_v2.TpuAsyncClient.list_nodes", + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.list_runtime_versions", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.ListNodes", + "fullName": "google.cloud.tpu.v2.Tpu.ListRuntimeVersions", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "ListNodes" + "shortName": "ListRuntimeVersions" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.ListNodesRequest" + "type": "google.cloud.tpu_v2.types.ListRuntimeVersionsRequest" }, { "name": "parent", @@ -1338,14 +2159,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListNodesAsyncPager", - "shortName": "list_nodes" + "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListRuntimeVersionsAsyncPager", + "shortName": "list_runtime_versions" }, - "description": "Sample for ListNodes", - "file": "tpu_v2_generated_tpu_list_nodes_async.py", + "description": "Sample for ListRuntimeVersions", + "file": "tpu_v2_generated_tpu_list_runtime_versions_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_ListNodes_async", + "regionTag": "tpu_v2_generated_Tpu_ListRuntimeVersions_async", "segments": [ { "end": 52, @@ -1378,7 +2199,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_list_nodes_async.py" + "title": "tpu_v2_generated_tpu_list_runtime_versions_async.py" }, { "canonical": true, @@ -1387,19 +2208,19 @@ "fullName": "google.cloud.tpu_v2.TpuClient", "shortName": "TpuClient" }, - "fullName": "google.cloud.tpu_v2.TpuClient.list_nodes", + "fullName": "google.cloud.tpu_v2.TpuClient.list_runtime_versions", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.ListNodes", + "fullName": "google.cloud.tpu.v2.Tpu.ListRuntimeVersions", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "ListNodes" + "shortName": "ListRuntimeVersions" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.ListNodesRequest" + "type": "google.cloud.tpu_v2.types.ListRuntimeVersionsRequest" }, { "name": "parent", @@ -1418,14 +2239,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListNodesPager", - "shortName": "list_nodes" + "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListRuntimeVersionsPager", + "shortName": "list_runtime_versions" }, - "description": "Sample for ListNodes", - "file": "tpu_v2_generated_tpu_list_nodes_sync.py", + "description": "Sample for ListRuntimeVersions", + "file": "tpu_v2_generated_tpu_list_runtime_versions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_ListNodes_sync", + "regionTag": "tpu_v2_generated_Tpu_ListRuntimeVersions_sync", "segments": [ { "end": 52, @@ -1458,7 +2279,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_list_nodes_sync.py" + "title": "tpu_v2_generated_tpu_list_runtime_versions_sync.py" }, { "canonical": true, @@ -1468,22 +2289,22 @@ "fullName": "google.cloud.tpu_v2.TpuAsyncClient", "shortName": "TpuAsyncClient" }, - "fullName": "google.cloud.tpu_v2.TpuAsyncClient.list_runtime_versions", + "fullName": "google.cloud.tpu_v2.TpuAsyncClient.reset_queued_resource", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.ListRuntimeVersions", + "fullName": "google.cloud.tpu.v2.Tpu.ResetQueuedResource", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "ListRuntimeVersions" + "shortName": "ResetQueuedResource" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.ListRuntimeVersionsRequest" + "type": "google.cloud.tpu_v2.types.ResetQueuedResourceRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -1499,22 +2320,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListRuntimeVersionsAsyncPager", - "shortName": "list_runtime_versions" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "reset_queued_resource" }, - "description": "Sample for ListRuntimeVersions", - "file": "tpu_v2_generated_tpu_list_runtime_versions_async.py", + "description": "Sample for ResetQueuedResource", + "file": "tpu_v2_generated_tpu_reset_queued_resource_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_ListRuntimeVersions_async", + "regionTag": "tpu_v2_generated_Tpu_ResetQueuedResource_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1529,17 +2350,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_list_runtime_versions_async.py" + "title": "tpu_v2_generated_tpu_reset_queued_resource_async.py" }, { "canonical": true, @@ -1548,22 +2369,22 @@ "fullName": "google.cloud.tpu_v2.TpuClient", "shortName": "TpuClient" }, - "fullName": "google.cloud.tpu_v2.TpuClient.list_runtime_versions", + "fullName": "google.cloud.tpu_v2.TpuClient.reset_queued_resource", "method": { - "fullName": "google.cloud.tpu.v2.Tpu.ListRuntimeVersions", + "fullName": "google.cloud.tpu.v2.Tpu.ResetQueuedResource", "service": { "fullName": "google.cloud.tpu.v2.Tpu", "shortName": "Tpu" }, - "shortName": "ListRuntimeVersions" + "shortName": "ResetQueuedResource" }, "parameters": [ { "name": "request", - "type": "google.cloud.tpu_v2.types.ListRuntimeVersionsRequest" + "type": "google.cloud.tpu_v2.types.ResetQueuedResourceRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -1579,22 +2400,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.tpu_v2.services.tpu.pagers.ListRuntimeVersionsPager", - "shortName": "list_runtime_versions" + "resultType": "google.api_core.operation.Operation", + "shortName": "reset_queued_resource" }, - "description": "Sample for ListRuntimeVersions", - "file": "tpu_v2_generated_tpu_list_runtime_versions_sync.py", + "description": "Sample for ResetQueuedResource", + "file": "tpu_v2_generated_tpu_reset_queued_resource_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "tpu_v2_generated_Tpu_ListRuntimeVersions_sync", + "regionTag": "tpu_v2_generated_Tpu_ResetQueuedResource_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1609,17 +2430,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "tpu_v2_generated_tpu_list_runtime_versions_sync.py" + "title": "tpu_v2_generated_tpu_reset_queued_resource_sync.py" }, { "canonical": true, diff --git a/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_create_queued_resource_async.py b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_create_queued_resource_async.py new file mode 100644 index 000000000000..60a438e859d8 --- /dev/null +++ b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_create_queued_resource_async.py @@ -0,0 +1,56 @@ +# -*- 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 CreateQueuedResource +# 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-tpu + + +# [START tpu_v2_generated_Tpu_CreateQueuedResource_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 tpu_v2 + + +async def sample_create_queued_resource(): + # Create a client + client = tpu_v2.TpuAsyncClient() + + # Initialize request argument(s) + request = tpu_v2.CreateQueuedResourceRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END tpu_v2_generated_Tpu_CreateQueuedResource_async] diff --git a/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_create_queued_resource_sync.py b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_create_queued_resource_sync.py new file mode 100644 index 000000000000..f2083377485c --- /dev/null +++ b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_create_queued_resource_sync.py @@ -0,0 +1,56 @@ +# -*- 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 CreateQueuedResource +# 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-tpu + + +# [START tpu_v2_generated_Tpu_CreateQueuedResource_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 tpu_v2 + + +def sample_create_queued_resource(): + # Create a client + client = tpu_v2.TpuClient() + + # Initialize request argument(s) + request = tpu_v2.CreateQueuedResourceRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END tpu_v2_generated_Tpu_CreateQueuedResource_sync] diff --git a/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_delete_queued_resource_async.py b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_delete_queued_resource_async.py new file mode 100644 index 000000000000..f6f8dfe2f789 --- /dev/null +++ b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_delete_queued_resource_async.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteQueuedResource +# 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-tpu + + +# [START tpu_v2_generated_Tpu_DeleteQueuedResource_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 tpu_v2 + + +async def sample_delete_queued_resource(): + # Create a client + client = tpu_v2.TpuAsyncClient() + + # Initialize request argument(s) + request = tpu_v2.DeleteQueuedResourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END tpu_v2_generated_Tpu_DeleteQueuedResource_async] diff --git a/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_delete_queued_resource_sync.py b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_delete_queued_resource_sync.py new file mode 100644 index 000000000000..bdcf9a1cf542 --- /dev/null +++ b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_delete_queued_resource_sync.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteQueuedResource +# 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-tpu + + +# [START tpu_v2_generated_Tpu_DeleteQueuedResource_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 tpu_v2 + + +def sample_delete_queued_resource(): + # Create a client + client = tpu_v2.TpuClient() + + # Initialize request argument(s) + request = tpu_v2.DeleteQueuedResourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END tpu_v2_generated_Tpu_DeleteQueuedResource_sync] diff --git a/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_get_queued_resource_async.py b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_get_queued_resource_async.py new file mode 100644 index 000000000000..ae86b5308327 --- /dev/null +++ b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_get_queued_resource_async.py @@ -0,0 +1,52 @@ +# -*- 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 GetQueuedResource +# 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-tpu + + +# [START tpu_v2_generated_Tpu_GetQueuedResource_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 tpu_v2 + + +async def sample_get_queued_resource(): + # Create a client + client = tpu_v2.TpuAsyncClient() + + # Initialize request argument(s) + request = tpu_v2.GetQueuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_queued_resource(request=request) + + # Handle the response + print(response) + +# [END tpu_v2_generated_Tpu_GetQueuedResource_async] diff --git a/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_get_queued_resource_sync.py b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_get_queued_resource_sync.py new file mode 100644 index 000000000000..860a534a42a6 --- /dev/null +++ b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_get_queued_resource_sync.py @@ -0,0 +1,52 @@ +# -*- 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 GetQueuedResource +# 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-tpu + + +# [START tpu_v2_generated_Tpu_GetQueuedResource_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 tpu_v2 + + +def sample_get_queued_resource(): + # Create a client + client = tpu_v2.TpuClient() + + # Initialize request argument(s) + request = tpu_v2.GetQueuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_queued_resource(request=request) + + # Handle the response + print(response) + +# [END tpu_v2_generated_Tpu_GetQueuedResource_sync] diff --git a/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_list_queued_resources_async.py b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_list_queued_resources_async.py new file mode 100644 index 000000000000..63edb3f0b268 --- /dev/null +++ b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_list_queued_resources_async.py @@ -0,0 +1,53 @@ +# -*- 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 ListQueuedResources +# 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-tpu + + +# [START tpu_v2_generated_Tpu_ListQueuedResources_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 tpu_v2 + + +async def sample_list_queued_resources(): + # Create a client + client = tpu_v2.TpuAsyncClient() + + # Initialize request argument(s) + request = tpu_v2.ListQueuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_queued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END tpu_v2_generated_Tpu_ListQueuedResources_async] diff --git a/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_list_queued_resources_sync.py b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_list_queued_resources_sync.py new file mode 100644 index 000000000000..ce99ca55c920 --- /dev/null +++ b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_list_queued_resources_sync.py @@ -0,0 +1,53 @@ +# -*- 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 ListQueuedResources +# 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-tpu + + +# [START tpu_v2_generated_Tpu_ListQueuedResources_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 tpu_v2 + + +def sample_list_queued_resources(): + # Create a client + client = tpu_v2.TpuClient() + + # Initialize request argument(s) + request = tpu_v2.ListQueuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_queued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END tpu_v2_generated_Tpu_ListQueuedResources_sync] diff --git a/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_reset_queued_resource_async.py b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_reset_queued_resource_async.py new file mode 100644 index 000000000000..b577ee51f4fb --- /dev/null +++ b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_reset_queued_resource_async.py @@ -0,0 +1,56 @@ +# -*- 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 ResetQueuedResource +# 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-tpu + + +# [START tpu_v2_generated_Tpu_ResetQueuedResource_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 tpu_v2 + + +async def sample_reset_queued_resource(): + # Create a client + client = tpu_v2.TpuAsyncClient() + + # Initialize request argument(s) + request = tpu_v2.ResetQueuedResourceRequest( + name="name_value", + ) + + # Make the request + operation = client.reset_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END tpu_v2_generated_Tpu_ResetQueuedResource_async] diff --git a/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_reset_queued_resource_sync.py b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_reset_queued_resource_sync.py new file mode 100644 index 000000000000..805a3f9004f8 --- /dev/null +++ b/packages/google-cloud-tpu/samples/generated_samples/tpu_v2_generated_tpu_reset_queued_resource_sync.py @@ -0,0 +1,56 @@ +# -*- 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 ResetQueuedResource +# 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-tpu + + +# [START tpu_v2_generated_Tpu_ResetQueuedResource_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 tpu_v2 + + +def sample_reset_queued_resource(): + # Create a client + client = tpu_v2.TpuClient() + + # Initialize request argument(s) + request = tpu_v2.ResetQueuedResourceRequest( + name="name_value", + ) + + # Make the request + operation = client.reset_queued_resource(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END tpu_v2_generated_Tpu_ResetQueuedResource_sync] diff --git a/packages/google-cloud-tpu/scripts/fixup_tpu_v2_keywords.py b/packages/google-cloud-tpu/scripts/fixup_tpu_v2_keywords.py index 9a800a02e50b..8e4b4b9f1d49 100644 --- a/packages/google-cloud-tpu/scripts/fixup_tpu_v2_keywords.py +++ b/packages/google-cloud-tpu/scripts/fixup_tpu_v2_keywords.py @@ -40,15 +40,20 @@ class tpuCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'create_node': ('parent', 'node', 'node_id', ), + 'create_queued_resource': ('parent', 'queued_resource', 'queued_resource_id', 'request_id', ), 'delete_node': ('name', ), + 'delete_queued_resource': ('name', 'request_id', 'force', ), 'generate_service_identity': ('parent', ), 'get_accelerator_type': ('name', ), 'get_guest_attributes': ('name', 'query_path', 'worker_ids', ), 'get_node': ('name', ), + 'get_queued_resource': ('name', ), 'get_runtime_version': ('name', ), 'list_accelerator_types': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_nodes': ('parent', 'page_size', 'page_token', ), + 'list_queued_resources': ('parent', 'page_size', 'page_token', ), 'list_runtime_versions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'reset_queued_resource': ('name', ), 'start_node': ('name', ), 'stop_node': ('name', ), 'update_node': ('update_mask', 'node', ), diff --git a/packages/google-cloud-tpu/tests/unit/gapic/tpu_v2/test_tpu.py b/packages/google-cloud-tpu/tests/unit/gapic/tpu_v2/test_tpu.py index f46c89530ed1..483c6e0b270f 100644 --- a/packages/google-cloud-tpu/tests/unit/gapic/tpu_v2/test_tpu.py +++ b/packages/google-cloud-tpu/tests/unit/gapic/tpu_v2/test_tpu.py @@ -62,9 +62,13 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import interval_pb2 # type: ignore from google.cloud.tpu_v2.services.tpu import ( TpuAsyncClient, @@ -3361,11 +3365,11 @@ async def test_update_node_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - cloud_tpu.GenerateServiceIdentityRequest, + cloud_tpu.ListQueuedResourcesRequest, dict, ], ) -def test_generate_service_identity(request_type, transport: str = "grpc"): +def test_list_queued_resources(request_type, transport: str = "grpc"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3377,23 +3381,28 @@ def test_generate_service_identity(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_service_identity), "__call__" + type(client.transport.list_queued_resources), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.GenerateServiceIdentityResponse() - response = client.generate_service_identity(request) + call.return_value = cloud_tpu.ListQueuedResourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_queued_resources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = cloud_tpu.GenerateServiceIdentityRequest() + request = cloud_tpu.ListQueuedResourcesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, cloud_tpu.GenerateServiceIdentityResponse) + assert isinstance(response, pagers.ListQueuedResourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_generate_service_identity_non_empty_request_with_auto_populated_field(): +def test_list_queued_resources_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 = TpuClient( @@ -3404,26 +3413,28 @@ def test_generate_service_identity_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_tpu.GenerateServiceIdentityRequest( + request = cloud_tpu.ListQueuedResourcesRequest( parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_service_identity), "__call__" + type(client.transport.list_queued_resources), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.generate_service_identity(request=request) + client.list_queued_resources(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_tpu.GenerateServiceIdentityRequest( + assert args[0] == cloud_tpu.ListQueuedResourcesRequest( parent="parent_value", + page_token="page_token_value", ) -def test_generate_service_identity_use_cached_wrapped_rpc(): +def test_list_queued_resources_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: @@ -3438,7 +3449,7 @@ def test_generate_service_identity_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.generate_service_identity + client._transport.list_queued_resources in client._transport._wrapped_methods ) @@ -3448,15 +3459,15 @@ def test_generate_service_identity_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.generate_service_identity + client._transport.list_queued_resources ] = mock_rpc request = {} - client.generate_service_identity(request) + client.list_queued_resources(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.generate_service_identity(request) + client.list_queued_resources(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3464,7 +3475,7 @@ def test_generate_service_identity_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_generate_service_identity_async_use_cached_wrapped_rpc( +async def test_list_queued_resources_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3481,7 +3492,7 @@ async def test_generate_service_identity_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.generate_service_identity + client._client._transport.list_queued_resources in client._client._transport._wrapped_methods ) @@ -3489,16 +3500,16 @@ async def test_generate_service_identity_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.generate_service_identity + client._client._transport.list_queued_resources ] = mock_rpc request = {} - await client.generate_service_identity(request) + await client.list_queued_resources(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.generate_service_identity(request) + await client.list_queued_resources(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3506,9 +3517,8 @@ async def test_generate_service_identity_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_generate_service_identity_async( - transport: str = "grpc_asyncio", - request_type=cloud_tpu.GenerateServiceIdentityRequest, +async def test_list_queued_resources_async( + transport: str = "grpc_asyncio", request_type=cloud_tpu.ListQueuedResourcesRequest ): client = TpuAsyncClient( credentials=async_anonymous_credentials(), @@ -3521,46 +3531,51 @@ async def test_generate_service_identity_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_service_identity), "__call__" + type(client.transport.list_queued_resources), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.GenerateServiceIdentityResponse() + cloud_tpu.ListQueuedResourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - response = await client.generate_service_identity(request) + response = await client.list_queued_resources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = cloud_tpu.GenerateServiceIdentityRequest() + request = cloud_tpu.ListQueuedResourcesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, cloud_tpu.GenerateServiceIdentityResponse) + assert isinstance(response, pagers.ListQueuedResourcesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_generate_service_identity_async_from_dict(): - await test_generate_service_identity_async(request_type=dict) +async def test_list_queued_resources_async_from_dict(): + await test_list_queued_resources_async(request_type=dict) -def test_generate_service_identity_field_headers(): +def test_list_queued_resources_field_headers(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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_tpu.GenerateServiceIdentityRequest() + request = cloud_tpu.ListQueuedResourcesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_service_identity), "__call__" + type(client.transport.list_queued_resources), "__call__" ) as call: - call.return_value = cloud_tpu.GenerateServiceIdentityResponse() - client.generate_service_identity(request) + call.return_value = cloud_tpu.ListQueuedResourcesResponse() + client.list_queued_resources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3576,25 +3591,25 @@ def test_generate_service_identity_field_headers(): @pytest.mark.asyncio -async def test_generate_service_identity_field_headers_async(): +async def test_list_queued_resources_field_headers_async(): client = TpuAsyncClient( 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_tpu.GenerateServiceIdentityRequest() + request = cloud_tpu.ListQueuedResourcesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_service_identity), "__call__" + type(client.transport.list_queued_resources), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.GenerateServiceIdentityResponse() + cloud_tpu.ListQueuedResourcesResponse() ) - await client.generate_service_identity(request) + await client.list_queued_resources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3609,392 +3624,126 @@ async def test_generate_service_identity_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - cloud_tpu.ListAcceleratorTypesRequest, - dict, - ], -) -def test_list_accelerator_types(request_type, transport: str = "grpc"): +def test_list_queued_resources_flattened(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_accelerator_types), "__call__" + type(client.transport.list_queued_resources), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.ListAcceleratorTypesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + call.return_value = cloud_tpu.ListQueuedResourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_queued_resources( + parent="parent_value", ) - response = client.list_accelerator_types(request) - # Establish that the underlying gRPC stub method was called. + # Establish that the underlying call was made with the expected + # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = cloud_tpu.ListAcceleratorTypesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAcceleratorTypesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_list_accelerator_types_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_list_queued_resources_flattened_error(): client = TpuClient( 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_tpu.ListAcceleratorTypesRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accelerator_types), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_accelerator_types(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_tpu.ListAcceleratorTypesRequest( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_queued_resources( + cloud_tpu.ListQueuedResourcesRequest(), parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", - ) - - -def test_list_accelerator_types_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 = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.list_accelerator_types - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_accelerator_types - ] = mock_rpc - request = {} - client.list_accelerator_types(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_accelerator_types(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_list_accelerator_types_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 = TpuAsyncClient( - 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.list_accelerator_types - 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.list_accelerator_types - ] = mock_rpc - - request = {} - await client.list_accelerator_types(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_accelerator_types(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_accelerator_types_async( - transport: str = "grpc_asyncio", request_type=cloud_tpu.ListAcceleratorTypesRequest -): +async def test_list_queued_resources_flattened_async(): client = TpuAsyncClient( 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.list_accelerator_types), "__call__" + type(client.transport.list_queued_resources), "__call__" ) as call: # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.ListQueuedResourcesResponse() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.ListAcceleratorTypesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + cloud_tpu.ListQueuedResourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_queued_resources( + parent="parent_value", ) - response = await client.list_accelerator_types(request) - # Establish that the underlying gRPC stub method was called. + # Establish that the underlying call was made with the expected + # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = cloud_tpu.ListAcceleratorTypesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAcceleratorTypesAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_list_accelerator_types_async_from_dict(): - await test_list_accelerator_types_async(request_type=dict) +async def test_list_queued_resources_flattened_error_async(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_queued_resources( + cloud_tpu.ListQueuedResourcesRequest(), + parent="parent_value", + ) -def test_list_accelerator_types_field_headers(): +def test_list_queued_resources_pager(transport_name: str = "grpc"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = cloud_tpu.ListAcceleratorTypesRequest() - - request.parent = "parent_value" - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_accelerator_types), "__call__" - ) as call: - call.return_value = cloud_tpu.ListAcceleratorTypesResponse() - client.list_accelerator_types(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_list_accelerator_types_field_headers_async(): - client = TpuAsyncClient( - 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_tpu.ListAcceleratorTypesRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accelerator_types), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.ListAcceleratorTypesResponse() - ) - await client.list_accelerator_types(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -def test_list_accelerator_types_flattened(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accelerator_types), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.ListAcceleratorTypesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_accelerator_types( - parent="parent_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - - -def test_list_accelerator_types_flattened_error(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_accelerator_types( - cloud_tpu.ListAcceleratorTypesRequest(), - parent="parent_value", - ) - - -@pytest.mark.asyncio -async def test_list_accelerator_types_flattened_async(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accelerator_types), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.ListAcceleratorTypesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.ListAcceleratorTypesResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_accelerator_types( - parent="parent_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_list_accelerator_types_flattened_error_async(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_accelerator_types( - cloud_tpu.ListAcceleratorTypesRequest(), - parent="parent_value", - ) - - -def test_list_accelerator_types_pager(transport_name: str = "grpc"): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accelerator_types), "__call__" + type(client.transport.list_queued_resources), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), ], next_page_token="abc", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[], + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[], next_page_token="def", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), ], next_page_token="ghi", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), ], ), RuntimeError, @@ -4006,7 +3755,7 @@ def test_list_accelerator_types_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_accelerator_types(request={}, retry=retry, timeout=timeout) + pager = client.list_queued_resources(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -4014,10 +3763,10 @@ def test_list_accelerator_types_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, cloud_tpu.AcceleratorType) for i in results) + assert all(isinstance(i, cloud_tpu.QueuedResource) for i in results) -def test_list_accelerator_types_pages(transport_name: str = "grpc"): +def test_list_queued_resources_pages(transport_name: str = "grpc"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -4025,82 +3774,82 @@ def test_list_accelerator_types_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_accelerator_types), "__call__" + type(client.transport.list_queued_resources), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), ], next_page_token="abc", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[], + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[], next_page_token="def", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), ], next_page_token="ghi", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), ], ), RuntimeError, ) - pages = list(client.list_accelerator_types(request={}).pages) + pages = list(client.list_queued_resources(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_accelerator_types_async_pager(): +async def test_list_queued_resources_async_pager(): client = TpuAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_accelerator_types), + type(client.transport.list_queued_resources), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), ], next_page_token="abc", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[], + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[], next_page_token="def", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), ], next_page_token="ghi", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), ], ), RuntimeError, ) - async_pager = await client.list_accelerator_types( + async_pager = await client.list_queued_resources( request={}, ) assert async_pager.next_page_token == "abc" @@ -4109,45 +3858,45 @@ async def test_list_accelerator_types_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, cloud_tpu.AcceleratorType) for i in responses) + assert all(isinstance(i, cloud_tpu.QueuedResource) for i in responses) @pytest.mark.asyncio -async def test_list_accelerator_types_async_pages(): +async def test_list_queued_resources_async_pages(): client = TpuAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_accelerator_types), + type(client.transport.list_queued_resources), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), ], next_page_token="abc", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[], + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[], next_page_token="def", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), ], next_page_token="ghi", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), ], ), RuntimeError, @@ -4156,7 +3905,7 @@ async def test_list_accelerator_types_async_pages(): # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 async for page_ in ( # pragma: no branch - await client.list_accelerator_types(request={}) + await client.list_queued_resources(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -4166,11 +3915,11 @@ async def test_list_accelerator_types_async_pages(): @pytest.mark.parametrize( "request_type", [ - cloud_tpu.GetAcceleratorTypeRequest, + cloud_tpu.GetQueuedResourceRequest, dict, ], ) -def test_get_accelerator_type(request_type, transport: str = "grpc"): +def test_get_queued_resource(request_type, transport: str = "grpc"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4182,28 +3931,28 @@ def test_get_accelerator_type(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_accelerator_type), "__call__" + type(client.transport.get_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.AcceleratorType( + call.return_value = cloud_tpu.QueuedResource( name="name_value", - type_="type__value", + reservation_name="reservation_name_value", ) - response = client.get_accelerator_type(request) + response = client.get_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = cloud_tpu.GetAcceleratorTypeRequest() + request = cloud_tpu.GetQueuedResourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, cloud_tpu.AcceleratorType) + assert isinstance(response, cloud_tpu.QueuedResource) assert response.name == "name_value" - assert response.type_ == "type__value" + assert response.reservation_name == "reservation_name_value" -def test_get_accelerator_type_non_empty_request_with_auto_populated_field(): +def test_get_queued_resource_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 = TpuClient( @@ -4214,26 +3963,26 @@ def test_get_accelerator_type_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_tpu.GetAcceleratorTypeRequest( + request = cloud_tpu.GetQueuedResourceRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_accelerator_type), "__call__" + type(client.transport.get_queued_resource), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_accelerator_type(request=request) + client.get_queued_resource(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_tpu.GetAcceleratorTypeRequest( + assert args[0] == cloud_tpu.GetQueuedResourceRequest( name="name_value", ) -def test_get_accelerator_type_use_cached_wrapped_rpc(): +def test_get_queued_resource_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: @@ -4248,7 +3997,7 @@ def test_get_accelerator_type_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_accelerator_type in client._transport._wrapped_methods + client._transport.get_queued_resource in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -4257,15 +4006,15 @@ def test_get_accelerator_type_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_accelerator_type + client._transport.get_queued_resource ] = mock_rpc request = {} - client.get_accelerator_type(request) + client.get_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_accelerator_type(request) + client.get_queued_resource(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4273,7 +4022,7 @@ def test_get_accelerator_type_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_accelerator_type_async_use_cached_wrapped_rpc( +async def test_get_queued_resource_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4290,7 +4039,7 @@ async def test_get_accelerator_type_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_accelerator_type + client._client._transport.get_queued_resource in client._client._transport._wrapped_methods ) @@ -4298,16 +4047,16 @@ async def test_get_accelerator_type_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_accelerator_type + client._client._transport.get_queued_resource ] = mock_rpc request = {} - await client.get_accelerator_type(request) + await client.get_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_accelerator_type(request) + await client.get_queued_resource(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4315,8 +4064,8 @@ async def test_get_accelerator_type_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_accelerator_type_async( - transport: str = "grpc_asyncio", request_type=cloud_tpu.GetAcceleratorTypeRequest +async def test_get_queued_resource_async( + transport: str = "grpc_asyncio", request_type=cloud_tpu.GetQueuedResourceRequest ): client = TpuAsyncClient( credentials=async_anonymous_credentials(), @@ -4329,51 +4078,51 @@ async def test_get_accelerator_type_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_accelerator_type), "__call__" + type(client.transport.get_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.AcceleratorType( + cloud_tpu.QueuedResource( name="name_value", - type_="type__value", + reservation_name="reservation_name_value", ) ) - response = await client.get_accelerator_type(request) + response = await client.get_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = cloud_tpu.GetAcceleratorTypeRequest() + request = cloud_tpu.GetQueuedResourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, cloud_tpu.AcceleratorType) + assert isinstance(response, cloud_tpu.QueuedResource) assert response.name == "name_value" - assert response.type_ == "type__value" + assert response.reservation_name == "reservation_name_value" @pytest.mark.asyncio -async def test_get_accelerator_type_async_from_dict(): - await test_get_accelerator_type_async(request_type=dict) +async def test_get_queued_resource_async_from_dict(): + await test_get_queued_resource_async(request_type=dict) -def test_get_accelerator_type_field_headers(): +def test_get_queued_resource_field_headers(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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_tpu.GetAcceleratorTypeRequest() + request = cloud_tpu.GetQueuedResourceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_accelerator_type), "__call__" + type(client.transport.get_queued_resource), "__call__" ) as call: - call.return_value = cloud_tpu.AcceleratorType() - client.get_accelerator_type(request) + call.return_value = cloud_tpu.QueuedResource() + client.get_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4389,25 +4138,25 @@ def test_get_accelerator_type_field_headers(): @pytest.mark.asyncio -async def test_get_accelerator_type_field_headers_async(): +async def test_get_queued_resource_field_headers_async(): client = TpuAsyncClient( 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_tpu.GetAcceleratorTypeRequest() + request = cloud_tpu.GetQueuedResourceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_accelerator_type), "__call__" + type(client.transport.get_queued_resource), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.AcceleratorType() + cloud_tpu.QueuedResource() ) - await client.get_accelerator_type(request) + await client.get_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4422,20 +4171,20 @@ async def test_get_accelerator_type_field_headers_async(): ) in kw["metadata"] -def test_get_accelerator_type_flattened(): +def test_get_queued_resource_flattened(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_accelerator_type), "__call__" + type(client.transport.get_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.AcceleratorType() + call.return_value = cloud_tpu.QueuedResource() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_accelerator_type( + client.get_queued_resource( name="name_value", ) @@ -4448,7 +4197,7 @@ def test_get_accelerator_type_flattened(): assert arg == mock_val -def test_get_accelerator_type_flattened_error(): +def test_get_queued_resource_flattened_error(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4456,31 +4205,31 @@ def test_get_accelerator_type_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_accelerator_type( - cloud_tpu.GetAcceleratorTypeRequest(), + client.get_queued_resource( + cloud_tpu.GetQueuedResourceRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_accelerator_type_flattened_async(): +async def test_get_queued_resource_flattened_async(): client = TpuAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_accelerator_type), "__call__" + type(client.transport.get_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.AcceleratorType() + call.return_value = cloud_tpu.QueuedResource() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.AcceleratorType() + cloud_tpu.QueuedResource() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_accelerator_type( + response = await client.get_queued_resource( name="name_value", ) @@ -4494,7 +4243,7 @@ async def test_get_accelerator_type_flattened_async(): @pytest.mark.asyncio -async def test_get_accelerator_type_flattened_error_async(): +async def test_get_queued_resource_flattened_error_async(): client = TpuAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4502,8 +4251,8 @@ async def test_get_accelerator_type_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.get_accelerator_type( - cloud_tpu.GetAcceleratorTypeRequest(), + await client.get_queued_resource( + cloud_tpu.GetQueuedResourceRequest(), name="name_value", ) @@ -4511,11 +4260,11 @@ async def test_get_accelerator_type_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - cloud_tpu.ListRuntimeVersionsRequest, + cloud_tpu.CreateQueuedResourceRequest, dict, ], ) -def test_list_runtime_versions(request_type, transport: str = "grpc"): +def test_create_queued_resource(request_type, transport: str = "grpc"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4527,28 +4276,23 @@ def test_list_runtime_versions(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_runtime_versions), "__call__" + type(client.transport.create_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.ListRuntimeVersionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - response = client.list_runtime_versions(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = cloud_tpu.ListRuntimeVersionsRequest() + request = cloud_tpu.CreateQueuedResourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRuntimeVersionsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) -def test_list_runtime_versions_non_empty_request_with_auto_populated_field(): +def test_create_queued_resource_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 = TpuClient( @@ -4559,32 +4303,30 @@ def test_list_runtime_versions_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_tpu.ListRuntimeVersionsRequest( + request = cloud_tpu.CreateQueuedResourceRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + queued_resource_id="queued_resource_id_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_runtime_versions), "__call__" + type(client.transport.create_queued_resource), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_runtime_versions(request=request) + client.create_queued_resource(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_tpu.ListRuntimeVersionsRequest( + assert args[0] == cloud_tpu.CreateQueuedResourceRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + queued_resource_id="queued_resource_id_value", + request_id="request_id_value", ) -def test_list_runtime_versions_use_cached_wrapped_rpc(): +def test_create_queued_resource_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: @@ -4599,7 +4341,7 @@ def test_list_runtime_versions_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_runtime_versions + client._transport.create_queued_resource in client._transport._wrapped_methods ) @@ -4609,15 +4351,20 @@ def test_list_runtime_versions_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_runtime_versions + client._transport.create_queued_resource ] = mock_rpc request = {} - client.list_runtime_versions(request) + client.create_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_runtime_versions(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_queued_resource(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4625,7 +4372,7 @@ def test_list_runtime_versions_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_runtime_versions_async_use_cached_wrapped_rpc( +async def test_create_queued_resource_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4642,7 +4389,7 @@ async def test_list_runtime_versions_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_runtime_versions + client._client._transport.create_queued_resource in client._client._transport._wrapped_methods ) @@ -4650,16 +4397,21 @@ async def test_list_runtime_versions_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_runtime_versions + client._client._transport.create_queued_resource ] = mock_rpc request = {} - await client.list_runtime_versions(request) + await client.create_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_runtime_versions(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_queued_resource(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4667,8 +4419,8 @@ async def test_list_runtime_versions_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_runtime_versions_async( - transport: str = "grpc_asyncio", request_type=cloud_tpu.ListRuntimeVersionsRequest +async def test_create_queued_resource_async( + transport: str = "grpc_asyncio", request_type=cloud_tpu.CreateQueuedResourceRequest ): client = TpuAsyncClient( credentials=async_anonymous_credentials(), @@ -4681,51 +4433,46 @@ async def test_list_runtime_versions_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_runtime_versions), "__call__" + type(client.transport.create_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.ListRuntimeVersionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_runtime_versions(request) + response = await client.create_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = cloud_tpu.ListRuntimeVersionsRequest() + request = cloud_tpu.CreateQueuedResourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRuntimeVersionsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_list_runtime_versions_async_from_dict(): - await test_list_runtime_versions_async(request_type=dict) +async def test_create_queued_resource_async_from_dict(): + await test_create_queued_resource_async(request_type=dict) -def test_list_runtime_versions_field_headers(): +def test_create_queued_resource_field_headers(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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_tpu.ListRuntimeVersionsRequest() + request = cloud_tpu.CreateQueuedResourceRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_runtime_versions), "__call__" + type(client.transport.create_queued_resource), "__call__" ) as call: - call.return_value = cloud_tpu.ListRuntimeVersionsResponse() - client.list_runtime_versions(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4741,25 +4488,25 @@ def test_list_runtime_versions_field_headers(): @pytest.mark.asyncio -async def test_list_runtime_versions_field_headers_async(): +async def test_create_queued_resource_field_headers_async(): client = TpuAsyncClient( 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_tpu.ListRuntimeVersionsRequest() + request = cloud_tpu.CreateQueuedResourceRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_runtime_versions), "__call__" + type(client.transport.create_queued_resource), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.ListRuntimeVersionsResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_runtime_versions(request) + await client.create_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4774,21 +4521,23 @@ async def test_list_runtime_versions_field_headers_async(): ) in kw["metadata"] -def test_list_runtime_versions_flattened(): +def test_create_queued_resource_flattened(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_runtime_versions), "__call__" + type(client.transport.create_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.ListRuntimeVersionsResponse() + 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.list_runtime_versions( + client.create_queued_resource( parent="parent_value", + queued_resource=cloud_tpu.QueuedResource(name="name_value"), + queued_resource_id="queued_resource_id_value", ) # Establish that the underlying call was made with the expected @@ -4798,9 +4547,15 @@ def test_list_runtime_versions_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].queued_resource + mock_val = cloud_tpu.QueuedResource(name="name_value") + assert arg == mock_val + arg = args[0].queued_resource_id + mock_val = "queued_resource_id_value" + assert arg == mock_val -def test_list_runtime_versions_flattened_error(): +def test_create_queued_resource_flattened_error(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4808,32 +4563,36 @@ def test_list_runtime_versions_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_runtime_versions( - cloud_tpu.ListRuntimeVersionsRequest(), + client.create_queued_resource( + cloud_tpu.CreateQueuedResourceRequest(), parent="parent_value", + queued_resource=cloud_tpu.QueuedResource(name="name_value"), + queued_resource_id="queued_resource_id_value", ) @pytest.mark.asyncio -async def test_list_runtime_versions_flattened_async(): +async def test_create_queued_resource_flattened_async(): client = TpuAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_runtime_versions), "__call__" + type(client.transport.create_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.ListRuntimeVersionsResponse() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.ListRuntimeVersionsResponse() + 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.list_runtime_versions( + response = await client.create_queued_resource( parent="parent_value", + queued_resource=cloud_tpu.QueuedResource(name="name_value"), + queued_resource_id="queued_resource_id_value", ) # Establish that the underlying call was made with the expected @@ -4843,10 +4602,16 @@ async def test_list_runtime_versions_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].queued_resource + mock_val = cloud_tpu.QueuedResource(name="name_value") + assert arg == mock_val + arg = args[0].queued_resource_id + mock_val = "queued_resource_id_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_list_runtime_versions_flattened_error_async(): +async def test_create_queued_resource_flattened_error_async(): client = TpuAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4854,292 +4619,89 @@ async def test_list_runtime_versions_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.list_runtime_versions( - cloud_tpu.ListRuntimeVersionsRequest(), + await client.create_queued_resource( + cloud_tpu.CreateQueuedResourceRequest(), parent="parent_value", + queued_resource=cloud_tpu.QueuedResource(name="name_value"), + queued_resource_id="queued_resource_id_value", ) -def test_list_runtime_versions_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.DeleteQueuedResourceRequest, + dict, + ], +) +def test_delete_queued_resource(request_type, transport: str = "grpc"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_runtime_versions), "__call__" + type(client.transport.delete_queued_resource), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - ], - next_page_token="abc", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[], - next_page_token="def", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - ], - next_page_token="ghi", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_runtime_versions(request={}, retry=retry, timeout=timeout) + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_queued_resource(request) - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = cloud_tpu.DeleteQueuedResourceRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, cloud_tpu.RuntimeVersion) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_list_runtime_versions_pages(transport_name: str = "grpc"): +def test_delete_queued_resource_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 = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + 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_tpu.DeleteQueuedResourceRequest( + name="name_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_runtime_versions), "__call__" + type(client.transport.delete_queued_resource), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - ], - next_page_token="abc", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[], - next_page_token="def", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - ], - next_page_token="ghi", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - ], - ), - RuntimeError, + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_queued_resource(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tpu.DeleteQueuedResourceRequest( + name="name_value", + request_id="request_id_value", ) - pages = list(client.list_runtime_versions(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -@pytest.mark.asyncio -async def test_list_runtime_versions_async_pager(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_runtime_versions), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - ], - next_page_token="abc", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[], - next_page_token="def", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - ], - next_page_token="ghi", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_runtime_versions( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, cloud_tpu.RuntimeVersion) for i in responses) - - -@pytest.mark.asyncio -async def test_list_runtime_versions_async_pages(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_runtime_versions), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - ], - next_page_token="abc", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[], - next_page_token="def", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - ], - next_page_token="ghi", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_runtime_versions(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_tpu.GetRuntimeVersionRequest, - dict, - ], -) -def test_get_runtime_version(request_type, transport: str = "grpc"): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_runtime_version), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.RuntimeVersion( - name="name_value", - version="version_value", - ) - response = client.get_runtime_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = cloud_tpu.GetRuntimeVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_tpu.RuntimeVersion) - assert response.name == "name_value" - assert response.version == "version_value" - - -def test_get_runtime_version_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 = TpuClient( - 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_tpu.GetRuntimeVersionRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_runtime_version), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_runtime_version(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_tpu.GetRuntimeVersionRequest( - name="name_value", - ) - - -def test_get_runtime_version_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 = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_delete_queued_resource_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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -5147,7 +4709,8 @@ def test_get_runtime_version_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_runtime_version in client._transport._wrapped_methods + client._transport.delete_queued_resource + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5156,15 +4719,20 @@ def test_get_runtime_version_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_runtime_version + client._transport.delete_queued_resource ] = mock_rpc request = {} - client.get_runtime_version(request) + client.delete_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_runtime_version(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_queued_resource(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5172,7 +4740,7 @@ def test_get_runtime_version_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_runtime_version_async_use_cached_wrapped_rpc( +async def test_delete_queued_resource_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5189,7 +4757,7 @@ async def test_get_runtime_version_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_runtime_version + client._client._transport.delete_queued_resource in client._client._transport._wrapped_methods ) @@ -5197,16 +4765,21 @@ async def test_get_runtime_version_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_runtime_version + client._client._transport.delete_queued_resource ] = mock_rpc request = {} - await client.get_runtime_version(request) + await client.delete_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_runtime_version(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_queued_resource(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5214,8 +4787,8 @@ async def test_get_runtime_version_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_runtime_version_async( - transport: str = "grpc_asyncio", request_type=cloud_tpu.GetRuntimeVersionRequest +async def test_delete_queued_resource_async( + transport: str = "grpc_asyncio", request_type=cloud_tpu.DeleteQueuedResourceRequest ): client = TpuAsyncClient( credentials=async_anonymous_credentials(), @@ -5228,51 +4801,46 @@ async def test_get_runtime_version_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_runtime_version), "__call__" + type(client.transport.delete_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.RuntimeVersion( - name="name_value", - version="version_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_runtime_version(request) + response = await client.delete_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = cloud_tpu.GetRuntimeVersionRequest() + request = cloud_tpu.DeleteQueuedResourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, cloud_tpu.RuntimeVersion) - assert response.name == "name_value" - assert response.version == "version_value" + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_get_runtime_version_async_from_dict(): - await test_get_runtime_version_async(request_type=dict) +async def test_delete_queued_resource_async_from_dict(): + await test_delete_queued_resource_async(request_type=dict) -def test_get_runtime_version_field_headers(): +def test_delete_queued_resource_field_headers(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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_tpu.GetRuntimeVersionRequest() + request = cloud_tpu.DeleteQueuedResourceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_runtime_version), "__call__" + type(client.transport.delete_queued_resource), "__call__" ) as call: - call.return_value = cloud_tpu.RuntimeVersion() - client.get_runtime_version(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5288,25 +4856,25 @@ def test_get_runtime_version_field_headers(): @pytest.mark.asyncio -async def test_get_runtime_version_field_headers_async(): +async def test_delete_queued_resource_field_headers_async(): client = TpuAsyncClient( 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_tpu.GetRuntimeVersionRequest() + request = cloud_tpu.DeleteQueuedResourceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_runtime_version), "__call__" + type(client.transport.delete_queued_resource), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.RuntimeVersion() + operations_pb2.Operation(name="operations/op") ) - await client.get_runtime_version(request) + await client.delete_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5321,20 +4889,20 @@ async def test_get_runtime_version_field_headers_async(): ) in kw["metadata"] -def test_get_runtime_version_flattened(): +def test_delete_queued_resource_flattened(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_runtime_version), "__call__" + type(client.transport.delete_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.RuntimeVersion() + 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.get_runtime_version( + client.delete_queued_resource( name="name_value", ) @@ -5347,7 +4915,7 @@ def test_get_runtime_version_flattened(): assert arg == mock_val -def test_get_runtime_version_flattened_error(): +def test_delete_queued_resource_flattened_error(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5355,31 +4923,31 @@ def test_get_runtime_version_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_runtime_version( - cloud_tpu.GetRuntimeVersionRequest(), + client.delete_queued_resource( + cloud_tpu.DeleteQueuedResourceRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_runtime_version_flattened_async(): +async def test_delete_queued_resource_flattened_async(): client = TpuAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_runtime_version), "__call__" + type(client.transport.delete_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.RuntimeVersion() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.RuntimeVersion() + 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.get_runtime_version( + response = await client.delete_queued_resource( name="name_value", ) @@ -5393,7 +4961,7 @@ async def test_get_runtime_version_flattened_async(): @pytest.mark.asyncio -async def test_get_runtime_version_flattened_error_async(): +async def test_delete_queued_resource_flattened_error_async(): client = TpuAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5401,8 +4969,8 @@ async def test_get_runtime_version_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.get_runtime_version( - cloud_tpu.GetRuntimeVersionRequest(), + await client.delete_queued_resource( + cloud_tpu.DeleteQueuedResourceRequest(), name="name_value", ) @@ -5410,11 +4978,11 @@ async def test_get_runtime_version_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - cloud_tpu.GetGuestAttributesRequest, + cloud_tpu.ResetQueuedResourceRequest, dict, ], ) -def test_get_guest_attributes(request_type, transport: str = "grpc"): +def test_reset_queued_resource(request_type, transport: str = "grpc"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5426,23 +4994,23 @@ def test_get_guest_attributes(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_guest_attributes), "__call__" + type(client.transport.reset_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = cloud_tpu.GetGuestAttributesResponse() - response = client.get_guest_attributes(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.reset_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = cloud_tpu.GetGuestAttributesRequest() + request = cloud_tpu.ResetQueuedResourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, cloud_tpu.GetGuestAttributesResponse) + assert isinstance(response, future.Future) -def test_get_guest_attributes_non_empty_request_with_auto_populated_field(): +def test_reset_queued_resource_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 = TpuClient( @@ -5453,28 +5021,26 @@ def test_get_guest_attributes_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_tpu.GetGuestAttributesRequest( + request = cloud_tpu.ResetQueuedResourceRequest( name="name_value", - query_path="query_path_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_guest_attributes), "__call__" + type(client.transport.reset_queued_resource), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_guest_attributes(request=request) + client.reset_queued_resource(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_tpu.GetGuestAttributesRequest( + assert args[0] == cloud_tpu.ResetQueuedResourceRequest( name="name_value", - query_path="query_path_value", ) -def test_get_guest_attributes_use_cached_wrapped_rpc(): +def test_reset_queued_resource_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: @@ -5489,7 +5055,8 @@ def test_get_guest_attributes_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_guest_attributes in client._transport._wrapped_methods + client._transport.reset_queued_resource + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5498,15 +5065,20 @@ def test_get_guest_attributes_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_guest_attributes + client._transport.reset_queued_resource ] = mock_rpc request = {} - client.get_guest_attributes(request) + client.reset_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_guest_attributes(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.reset_queued_resource(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5514,7 +5086,7 @@ def test_get_guest_attributes_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_guest_attributes_async_use_cached_wrapped_rpc( +async def test_reset_queued_resource_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5531,7 +5103,7 @@ async def test_get_guest_attributes_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_guest_attributes + client._client._transport.reset_queued_resource in client._client._transport._wrapped_methods ) @@ -5539,16 +5111,21 @@ async def test_get_guest_attributes_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_guest_attributes + client._client._transport.reset_queued_resource ] = mock_rpc request = {} - await client.get_guest_attributes(request) + await client.reset_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_guest_attributes(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.reset_queued_resource(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5556,8 +5133,8 @@ async def test_get_guest_attributes_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_guest_attributes_async( - transport: str = "grpc_asyncio", request_type=cloud_tpu.GetGuestAttributesRequest +async def test_reset_queued_resource_async( + transport: str = "grpc_asyncio", request_type=cloud_tpu.ResetQueuedResourceRequest ): client = TpuAsyncClient( credentials=async_anonymous_credentials(), @@ -5570,46 +5147,46 @@ async def test_get_guest_attributes_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_guest_attributes), "__call__" + type(client.transport.reset_queued_resource), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.GetGuestAttributesResponse() + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_guest_attributes(request) + response = await client.reset_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = cloud_tpu.GetGuestAttributesRequest() + request = cloud_tpu.ResetQueuedResourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, cloud_tpu.GetGuestAttributesResponse) + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_get_guest_attributes_async_from_dict(): - await test_get_guest_attributes_async(request_type=dict) +async def test_reset_queued_resource_async_from_dict(): + await test_reset_queued_resource_async(request_type=dict) -def test_get_guest_attributes_field_headers(): +def test_reset_queued_resource_field_headers(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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_tpu.GetGuestAttributesRequest() + request = cloud_tpu.ResetQueuedResourceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_guest_attributes), "__call__" + type(client.transport.reset_queued_resource), "__call__" ) as call: - call.return_value = cloud_tpu.GetGuestAttributesResponse() - client.get_guest_attributes(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.reset_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5625,25 +5202,25 @@ def test_get_guest_attributes_field_headers(): @pytest.mark.asyncio -async def test_get_guest_attributes_field_headers_async(): +async def test_reset_queued_resource_field_headers_async(): client = TpuAsyncClient( 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_tpu.GetGuestAttributesRequest() + request = cloud_tpu.ResetQueuedResourceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_guest_attributes), "__call__" + type(client.transport.reset_queued_resource), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.GetGuestAttributesResponse() + operations_pb2.Operation(name="operations/op") ) - await client.get_guest_attributes(request) + await client.reset_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5658,13 +5235,164 @@ async def test_get_guest_attributes_field_headers_async(): ) in kw["metadata"] -def test_list_nodes_rest_use_cached_wrapped_rpc(): +def test_reset_queued_resource_flattened(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reset_queued_resource), "__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.reset_queued_resource( + 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_reset_queued_resource_flattened_error(): + client = TpuClient( + 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.reset_queued_resource( + cloud_tpu.ResetQueuedResourceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_reset_queued_resource_flattened_async(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reset_queued_resource), "__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.reset_queued_resource( + 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_reset_queued_resource_flattened_error_async(): + client = TpuAsyncClient( + 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.reset_queued_resource( + cloud_tpu.ResetQueuedResourceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.GenerateServiceIdentityRequest, + dict, + ], +) +def test_generate_service_identity(request_type, transport: str = "grpc"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_service_identity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.GenerateServiceIdentityResponse() + response = client.generate_service_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = cloud_tpu.GenerateServiceIdentityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_tpu.GenerateServiceIdentityResponse) + + +def test_generate_service_identity_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 = TpuClient( + 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_tpu.GenerateServiceIdentityRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_service_identity), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.generate_service_identity(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tpu.GenerateServiceIdentityRequest( + parent="parent_value", + ) + + +def test_generate_service_identity_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 = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -5672,250 +5400,261 @@ def test_list_nodes_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_nodes in client._transport._wrapped_methods + assert ( + client._transport.generate_service_identity + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_nodes] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.generate_service_identity + ] = mock_rpc request = {} - client.list_nodes(request) + client.generate_service_identity(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_nodes(request) + client.generate_service_identity(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_nodes_rest_required_fields(request_type=cloud_tpu.ListNodesRequest): - transport_class = transports.TpuRestTransport +@pytest.mark.asyncio +async def test_generate_service_identity_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 = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.generate_service_identity + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_nodes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.generate_service_identity + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.generate_service_identity(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_nodes._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) + await client.generate_service_identity(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = cloud_tpu.ListNodesResponse() - # 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_tpu.ListNodesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_generate_service_identity_async( + transport: str = "grpc_asyncio", + request_type=cloud_tpu.GenerateServiceIdentityRequest, +): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.list_nodes(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_service_identity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.GenerateServiceIdentityResponse() + ) + response = await client.generate_service_identity(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = cloud_tpu.GenerateServiceIdentityRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_tpu.GenerateServiceIdentityResponse) -def test_list_nodes_rest_unset_required_fields(): - transport = transports.TpuRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.list_nodes._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) +@pytest.mark.asyncio +async def test_generate_service_identity_async_from_dict(): + await test_generate_service_identity_async(request_type=dict) -def test_list_nodes_rest_flattened(): +def test_generate_service_identity_field_headers(): client = TpuClient( 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 = cloud_tpu.ListNodesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Any value 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_tpu.GenerateServiceIdentityRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + request.parent = "parent_value" - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_tpu.ListNodesResponse.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.generate_service_identity), "__call__" + ) as call: + call.return_value = cloud_tpu.GenerateServiceIdentityResponse() + client.generate_service_identity(request) - client.list_nodes(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*/locations/*}/nodes" % client.transport._host, - args[1], - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_list_nodes_rest_flattened_error(transport: str = "rest"): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_generate_service_identity_field_headers_async(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_nodes( - cloud_tpu.ListNodesRequest(), - parent="parent_value", + # Any value 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_tpu.GenerateServiceIdentityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_service_identity), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.GenerateServiceIdentityResponse() ) + await client.generate_service_identity(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_list_nodes_rest_pager(transport: str = "rest"): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.ListAcceleratorTypesRequest, + dict, + ], +) +def test_list_accelerator_types(request_type, transport: str = "grpc"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - cloud_tpu.ListNodesResponse( - nodes=[ - cloud_tpu.Node(), - cloud_tpu.Node(), - cloud_tpu.Node(), - ], - next_page_token="abc", - ), - cloud_tpu.ListNodesResponse( - nodes=[], - next_page_token="def", - ), - cloud_tpu.ListNodesResponse( - nodes=[ - cloud_tpu.Node(), - ], - next_page_token="ghi", - ), - cloud_tpu.ListNodesResponse( - nodes=[ - cloud_tpu.Node(), - cloud_tpu.Node(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Wrap the values into proper Response objs - response = tuple(cloud_tpu.ListNodesResponse.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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.ListAcceleratorTypesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_accelerator_types(request) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = cloud_tpu.ListAcceleratorTypesRequest() + assert args[0] == request - pager = client.list_nodes(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAcceleratorTypesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, cloud_tpu.Node) for i in results) - pages = list(client.list_nodes(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +def test_list_accelerator_types_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 = TpuClient( + 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_tpu.ListAcceleratorTypesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) -def test_get_node_rest_use_cached_wrapped_rpc(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_accelerator_types(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tpu.ListAcceleratorTypesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_accelerator_types_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 = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -5923,397 +5662,3878 @@ def test_get_node_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_node in client._transport._wrapped_methods + assert ( + client._transport.list_accelerator_types + 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_node] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.list_accelerator_types + ] = mock_rpc request = {} - client.get_node(request) + client.list_accelerator_types(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_node(request) + client.list_accelerator_types(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_node_rest_required_fields(request_type=cloud_tpu.GetNodeRequest): - transport_class = transports.TpuRestTransport +@pytest.mark.asyncio +async def test_list_accelerator_types_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 = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.list_accelerator_types + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_node._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_accelerator_types + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_accelerator_types(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_node._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + await client.list_accelerator_types(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +async def test_list_accelerator_types_async( + transport: str = "grpc_asyncio", request_type=cloud_tpu.ListAcceleratorTypesRequest +): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = cloud_tpu.Node() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.ListAcceleratorTypesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_accelerator_types(request) - # Convert return value to protobuf type - return_value = cloud_tpu.Node.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = cloud_tpu.ListAcceleratorTypesRequest() + 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, pagers.ListAcceleratorTypesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - response = client.get_node(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_list_accelerator_types_async_from_dict(): + await test_list_accelerator_types_async(request_type=dict) -def test_get_node_rest_unset_required_fields(): - transport = transports.TpuRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_list_accelerator_types_field_headers(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.get_node._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloud_tpu.ListAcceleratorTypesRequest() + request.parent = "parent_value" -def test_get_node_rest_flattened(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), "__call__" + ) as call: + call.return_value = cloud_tpu.ListAcceleratorTypesResponse() + client.list_accelerator_types(request) - # 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_tpu.Node() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/nodes/sample3"} + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_tpu.Node.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"} +@pytest.mark.asyncio +async def test_list_accelerator_types_field_headers_async(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) - client.get_node(**mock_args) + # Any value 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_tpu.ListAcceleratorTypesRequest() - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{name=projects/*/locations/*/nodes/*}" % client.transport._host, - args[1], + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.ListAcceleratorTypesResponse() ) + await client.list_accelerator_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_get_node_rest_flattened_error(transport: str = "rest"): +def test_list_accelerator_types_flattened(): client = TpuClient( 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_node( - cloud_tpu.GetNodeRequest(), - name="name_value", - ) - - -def test_create_node_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 = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_node 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. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.ListAcceleratorTypesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_accelerator_types( + parent="parent_value", ) - client._transport._wrapped_methods[client._transport.create_node] = mock_rpc - - request = {} - client.create_node(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_node(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_node_rest_required_fields(request_type=cloud_tpu.CreateNodeRequest): - transport_class = transports.TpuRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_node._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_node._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("node_id",)) - jsonified_request.update(unset_fields) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_list_accelerator_types_flattened_error(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_node(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_create_node_rest_unset_required_fields(): - transport = transports.TpuRestTransport( - credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_node._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("nodeId",)) - & set( - ( - "parent", - "node", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_accelerator_types( + cloud_tpu.ListAcceleratorTypesRequest(), + parent="parent_value", ) - ) -def test_create_node_rest_flattened(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_accelerator_types_flattened_async(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.ListAcceleratorTypesResponse() - # get truthy value for each flattened field - mock_args = dict( + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.ListAcceleratorTypesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_accelerator_types( parent="parent_value", - node=cloud_tpu.Node(name="name_value"), - node_id="node_id_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_node(**mock_args) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*/locations/*}/nodes" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_create_node_rest_flattened_error(transport: str = "rest"): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_accelerator_types_flattened_error_async(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_node( - cloud_tpu.CreateNodeRequest(), + await client.list_accelerator_types( + cloud_tpu.ListAcceleratorTypesRequest(), parent="parent_value", - node=cloud_tpu.Node(name="name_value"), - node_id="node_id_value", - ) - - -def test_delete_node_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 = TpuClient( - 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_node 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_node] = mock_rpc - request = {} - client.delete_node(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_node(request) +def test_list_accelerator_types_pager(transport_name: str = "grpc"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) - # Establish that a new wrapper was not created for this call + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + ], + next_page_token="abc", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[], + next_page_token="def", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_accelerator_types(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_tpu.AcceleratorType) for i in results) + + +def test_list_accelerator_types_pages(transport_name: str = "grpc"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + ], + next_page_token="abc", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[], + next_page_token="def", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + ], + ), + RuntimeError, + ) + pages = list(client.list_accelerator_types(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_accelerator_types_async_pager(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + ], + next_page_token="abc", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[], + next_page_token="def", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_accelerator_types( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, cloud_tpu.AcceleratorType) for i in responses) + + +@pytest.mark.asyncio +async def test_list_accelerator_types_async_pages(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + ], + next_page_token="abc", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[], + next_page_token="def", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_accelerator_types(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.GetAcceleratorTypeRequest, + dict, + ], +) +def test_get_accelerator_type(request_type, transport: str = "grpc"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_accelerator_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.AcceleratorType( + name="name_value", + type_="type__value", + ) + response = client.get_accelerator_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = cloud_tpu.GetAcceleratorTypeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_tpu.AcceleratorType) + assert response.name == "name_value" + assert response.type_ == "type__value" + + +def test_get_accelerator_type_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 = TpuClient( + 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_tpu.GetAcceleratorTypeRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_accelerator_type), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_accelerator_type(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tpu.GetAcceleratorTypeRequest( + name="name_value", + ) + + +def test_get_accelerator_type_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 = TpuClient( + 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_accelerator_type 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_accelerator_type + ] = mock_rpc + request = {} + client.get_accelerator_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_accelerator_type(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_accelerator_type_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 = TpuAsyncClient( + 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_accelerator_type + 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_accelerator_type + ] = mock_rpc + + request = {} + await client.get_accelerator_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_accelerator_type(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_accelerator_type_async( + transport: str = "grpc_asyncio", request_type=cloud_tpu.GetAcceleratorTypeRequest +): + client = TpuAsyncClient( + 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_accelerator_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.AcceleratorType( + name="name_value", + type_="type__value", + ) + ) + response = await client.get_accelerator_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = cloud_tpu.GetAcceleratorTypeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_tpu.AcceleratorType) + assert response.name == "name_value" + assert response.type_ == "type__value" + + +@pytest.mark.asyncio +async def test_get_accelerator_type_async_from_dict(): + await test_get_accelerator_type_async(request_type=dict) + + +def test_get_accelerator_type_field_headers(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tpu.GetAcceleratorTypeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_accelerator_type), "__call__" + ) as call: + call.return_value = cloud_tpu.AcceleratorType() + client.get_accelerator_type(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_accelerator_type_field_headers_async(): + client = TpuAsyncClient( + 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_tpu.GetAcceleratorTypeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_accelerator_type), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.AcceleratorType() + ) + await client.get_accelerator_type(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_accelerator_type_flattened(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_accelerator_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.AcceleratorType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_accelerator_type( + 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_accelerator_type_flattened_error(): + client = TpuClient( + 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_accelerator_type( + cloud_tpu.GetAcceleratorTypeRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_accelerator_type_flattened_async(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_accelerator_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.AcceleratorType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.AcceleratorType() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_accelerator_type( + 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_accelerator_type_flattened_error_async(): + client = TpuAsyncClient( + 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_accelerator_type( + cloud_tpu.GetAcceleratorTypeRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.ListRuntimeVersionsRequest, + dict, + ], +) +def test_list_runtime_versions(request_type, transport: str = "grpc"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtime_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.ListRuntimeVersionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_runtime_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = cloud_tpu.ListRuntimeVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRuntimeVersionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_runtime_versions_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 = TpuClient( + 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_tpu.ListRuntimeVersionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtime_versions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_runtime_versions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tpu.ListRuntimeVersionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_runtime_versions_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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_runtime_versions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_runtime_versions + ] = mock_rpc + request = {} + client.list_runtime_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_runtime_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_runtime_versions_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 = TpuAsyncClient( + 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.list_runtime_versions + 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.list_runtime_versions + ] = mock_rpc + + request = {} + await client.list_runtime_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_runtime_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_runtime_versions_async( + transport: str = "grpc_asyncio", request_type=cloud_tpu.ListRuntimeVersionsRequest +): + client = TpuAsyncClient( + 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.list_runtime_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.ListRuntimeVersionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_runtime_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = cloud_tpu.ListRuntimeVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRuntimeVersionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_runtime_versions_async_from_dict(): + await test_list_runtime_versions_async(request_type=dict) + + +def test_list_runtime_versions_field_headers(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tpu.ListRuntimeVersionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtime_versions), "__call__" + ) as call: + call.return_value = cloud_tpu.ListRuntimeVersionsResponse() + client.list_runtime_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_runtime_versions_field_headers_async(): + client = TpuAsyncClient( + 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_tpu.ListRuntimeVersionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtime_versions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.ListRuntimeVersionsResponse() + ) + await client.list_runtime_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_runtime_versions_flattened(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtime_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.ListRuntimeVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_runtime_versions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_runtime_versions_flattened_error(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_runtime_versions( + cloud_tpu.ListRuntimeVersionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_runtime_versions_flattened_async(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtime_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.ListRuntimeVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.ListRuntimeVersionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_runtime_versions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_runtime_versions_flattened_error_async(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_runtime_versions( + cloud_tpu.ListRuntimeVersionsRequest(), + parent="parent_value", + ) + + +def test_list_runtime_versions_pager(transport_name: str = "grpc"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtime_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + ], + next_page_token="abc", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[], + next_page_token="def", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_runtime_versions(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_tpu.RuntimeVersion) for i in results) + + +def test_list_runtime_versions_pages(transport_name: str = "grpc"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtime_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + ], + next_page_token="abc", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[], + next_page_token="def", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_runtime_versions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_runtime_versions_async_pager(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtime_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + ], + next_page_token="abc", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[], + next_page_token="def", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_runtime_versions( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, cloud_tpu.RuntimeVersion) for i in responses) + + +@pytest.mark.asyncio +async def test_list_runtime_versions_async_pages(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_runtime_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + ], + next_page_token="abc", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[], + next_page_token="def", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_runtime_versions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.GetRuntimeVersionRequest, + dict, + ], +) +def test_get_runtime_version(request_type, transport: str = "grpc"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_runtime_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.RuntimeVersion( + name="name_value", + version="version_value", + ) + response = client.get_runtime_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = cloud_tpu.GetRuntimeVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_tpu.RuntimeVersion) + assert response.name == "name_value" + assert response.version == "version_value" + + +def test_get_runtime_version_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 = TpuClient( + 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_tpu.GetRuntimeVersionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_runtime_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_runtime_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tpu.GetRuntimeVersionRequest( + name="name_value", + ) + + +def test_get_runtime_version_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 = TpuClient( + 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_runtime_version 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_runtime_version + ] = mock_rpc + request = {} + client.get_runtime_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_runtime_version(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_runtime_version_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 = TpuAsyncClient( + 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_runtime_version + 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_runtime_version + ] = mock_rpc + + request = {} + await client.get_runtime_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_runtime_version(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_runtime_version_async( + transport: str = "grpc_asyncio", request_type=cloud_tpu.GetRuntimeVersionRequest +): + client = TpuAsyncClient( + 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_runtime_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.RuntimeVersion( + name="name_value", + version="version_value", + ) + ) + response = await client.get_runtime_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = cloud_tpu.GetRuntimeVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_tpu.RuntimeVersion) + assert response.name == "name_value" + assert response.version == "version_value" + + +@pytest.mark.asyncio +async def test_get_runtime_version_async_from_dict(): + await test_get_runtime_version_async(request_type=dict) + + +def test_get_runtime_version_field_headers(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tpu.GetRuntimeVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_runtime_version), "__call__" + ) as call: + call.return_value = cloud_tpu.RuntimeVersion() + client.get_runtime_version(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_runtime_version_field_headers_async(): + client = TpuAsyncClient( + 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_tpu.GetRuntimeVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_runtime_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.RuntimeVersion() + ) + await client.get_runtime_version(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_runtime_version_flattened(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_runtime_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.RuntimeVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_runtime_version( + 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_runtime_version_flattened_error(): + client = TpuClient( + 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_runtime_version( + cloud_tpu.GetRuntimeVersionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_runtime_version_flattened_async(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_runtime_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.RuntimeVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.RuntimeVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_runtime_version( + 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_runtime_version_flattened_error_async(): + client = TpuAsyncClient( + 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_runtime_version( + cloud_tpu.GetRuntimeVersionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.GetGuestAttributesRequest, + dict, + ], +) +def test_get_guest_attributes(request_type, transport: str = "grpc"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_guest_attributes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloud_tpu.GetGuestAttributesResponse() + response = client.get_guest_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = cloud_tpu.GetGuestAttributesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_tpu.GetGuestAttributesResponse) + + +def test_get_guest_attributes_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 = TpuClient( + 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_tpu.GetGuestAttributesRequest( + name="name_value", + query_path="query_path_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_guest_attributes), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_guest_attributes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tpu.GetGuestAttributesRequest( + name="name_value", + query_path="query_path_value", + ) + + +def test_get_guest_attributes_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 = TpuClient( + 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_guest_attributes 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_guest_attributes + ] = mock_rpc + request = {} + client.get_guest_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_guest_attributes(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_guest_attributes_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 = TpuAsyncClient( + 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_guest_attributes + 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_guest_attributes + ] = mock_rpc + + request = {} + await client.get_guest_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_guest_attributes(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_guest_attributes_async( + transport: str = "grpc_asyncio", request_type=cloud_tpu.GetGuestAttributesRequest +): + client = TpuAsyncClient( + 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_guest_attributes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.GetGuestAttributesResponse() + ) + response = await client.get_guest_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = cloud_tpu.GetGuestAttributesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_tpu.GetGuestAttributesResponse) + + +@pytest.mark.asyncio +async def test_get_guest_attributes_async_from_dict(): + await test_get_guest_attributes_async(request_type=dict) + + +def test_get_guest_attributes_field_headers(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tpu.GetGuestAttributesRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_guest_attributes), "__call__" + ) as call: + call.return_value = cloud_tpu.GetGuestAttributesResponse() + client.get_guest_attributes(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_guest_attributes_field_headers_async(): + client = TpuAsyncClient( + 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_tpu.GetGuestAttributesRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_guest_attributes), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.GetGuestAttributesResponse() + ) + await client.get_guest_attributes(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_list_nodes_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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_nodes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_nodes] = mock_rpc + + request = {} + client.list_nodes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_nodes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_nodes_rest_required_fields(request_type=cloud_tpu.ListNodesRequest): + transport_class = transports.TpuRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_nodes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_nodes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_tpu.ListNodesResponse() + # 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_tpu.ListNodesResponse.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_nodes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_nodes_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_nodes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_nodes_rest_flattened(): + client = TpuClient( + 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 = cloud_tpu.ListNodesResponse() + + # 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) + + # 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_tpu.ListNodesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_nodes(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/nodes" % client.transport._host, + args[1], + ) + + +def test_list_nodes_rest_flattened_error(transport: str = "rest"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_nodes( + cloud_tpu.ListNodesRequest(), + parent="parent_value", + ) + + +def test_list_nodes_rest_pager(transport: str = "rest"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + cloud_tpu.ListNodesResponse( + nodes=[ + cloud_tpu.Node(), + cloud_tpu.Node(), + cloud_tpu.Node(), + ], + next_page_token="abc", + ), + cloud_tpu.ListNodesResponse( + nodes=[], + next_page_token="def", + ), + cloud_tpu.ListNodesResponse( + nodes=[ + cloud_tpu.Node(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListNodesResponse( + nodes=[ + cloud_tpu.Node(), + cloud_tpu.Node(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(cloud_tpu.ListNodesResponse.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_nodes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_tpu.Node) for i in results) + + pages = list(client.list_nodes(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_node_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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_node 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_node] = mock_rpc + + request = {} + client.get_node(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_node(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_node_rest_required_fields(request_type=cloud_tpu.GetNodeRequest): + transport_class = transports.TpuRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_node._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_node._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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_tpu.Node() + # 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_tpu.Node.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_node(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_node_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_node._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_node_rest_flattened(): + client = TpuClient( + 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 = cloud_tpu.Node() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/nodes/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_tpu.Node.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_node(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/nodes/*}" % client.transport._host, + args[1], + ) + + +def test_get_node_rest_flattened_error(transport: str = "rest"): + client = TpuClient( + 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_node( + cloud_tpu.GetNodeRequest(), + name="name_value", + ) + + +def test_create_node_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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_node in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_node] = mock_rpc + + request = {} + client.create_node(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_node(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_node_rest_required_fields(request_type=cloud_tpu.CreateNodeRequest): + transport_class = transports.TpuRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_node._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_node._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("node_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_node(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_node_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_node._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("nodeId",)) + & set( + ( + "parent", + "node", + ) + ) + ) + + +def test_create_node_rest_flattened(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + node=cloud_tpu.Node(name="name_value"), + node_id="node_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_node(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/nodes" % client.transport._host, + args[1], + ) + + +def test_create_node_rest_flattened_error(transport: str = "rest"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_node( + cloud_tpu.CreateNodeRequest(), + parent="parent_value", + node=cloud_tpu.Node(name="name_value"), + node_id="node_id_value", + ) + + +def test_delete_node_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 = TpuClient( + 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_node 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_node] = mock_rpc + + request = {} + client.delete_node(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_node(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_node_rest_required_fields(request_type=cloud_tpu.DeleteNodeRequest): + transport_class = transports.TpuRestTransport + + 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_node._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_node._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 = TpuClient( + 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_node(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_node_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_node._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_node_rest_flattened(): + client = TpuClient( + 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/nodes/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_node(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/nodes/*}" % client.transport._host, + args[1], + ) + + +def test_delete_node_rest_flattened_error(transport: str = "rest"): + client = TpuClient( + 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_node( + cloud_tpu.DeleteNodeRequest(), + name="name_value", + ) + + +def test_stop_node_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 = TpuClient( + 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.stop_node 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.stop_node] = mock_rpc + + request = {} + client.stop_node(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.stop_node(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_stop_node_rest_required_fields(request_type=cloud_tpu.StopNodeRequest): + transport_class = transports.TpuRestTransport + + 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() + ).stop_node._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() + ).stop_node._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 = TpuClient( + 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.stop_node(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_stop_node_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.stop_node._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_start_node_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 = TpuClient( + 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.start_node 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.start_node] = mock_rpc + + request = {} + client.start_node(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.start_node(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_start_node_rest_required_fields(request_type=cloud_tpu.StartNodeRequest): + transport_class = transports.TpuRestTransport + + 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() + ).start_node._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() + ).start_node._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 = TpuClient( + 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.start_node(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_start_node_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.start_node._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_update_node_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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_node in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_node] = mock_rpc + + request = {} + client.update_node(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_node(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_node_rest_required_fields(request_type=cloud_tpu.UpdateNodeRequest): + transport_class = transports.TpuRestTransport + + 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_node._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_node._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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_node(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_node_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_node._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "updateMask", + "node", + ) + ) + ) + + +def test_update_node_rest_flattened(): + client = TpuClient( + 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 = { + "node": {"name": "projects/sample1/locations/sample2/nodes/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + node=cloud_tpu.Node(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_node(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{node.name=projects/*/locations/*/nodes/*}" % client.transport._host, + args[1], + ) + + +def test_update_node_rest_flattened_error(transport: str = "rest"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_node( + cloud_tpu.UpdateNodeRequest(), + node=cloud_tpu.Node(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_list_queued_resources_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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_queued_resources + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_queued_resources + ] = mock_rpc + + request = {} + client.list_queued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_queued_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_queued_resources_rest_required_fields( + request_type=cloud_tpu.ListQueuedResourcesRequest, +): + transport_class = transports.TpuRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_queued_resources._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_queued_resources._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_tpu.ListQueuedResourcesResponse() + # 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_tpu.ListQueuedResourcesResponse.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_queued_resources(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_queued_resources_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_queued_resources._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_queued_resources_rest_flattened(): + client = TpuClient( + 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 = cloud_tpu.ListQueuedResourcesResponse() + + # 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) + + # 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_tpu.ListQueuedResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_queued_resources(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/queuedResources" + % client.transport._host, + args[1], + ) + + +def test_list_queued_resources_rest_flattened_error(transport: str = "rest"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_queued_resources( + cloud_tpu.ListQueuedResourcesRequest(), + parent="parent_value", + ) + + +def test_list_queued_resources_rest_pager(transport: str = "rest"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), + ], + next_page_token="abc", + ), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[], + next_page_token="def", + ), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListQueuedResourcesResponse( + queued_resources=[ + cloud_tpu.QueuedResource(), + cloud_tpu.QueuedResource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_tpu.ListQueuedResourcesResponse.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_queued_resources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_tpu.QueuedResource) for i in results) + + pages = list(client.list_queued_resources(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_queued_resource_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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_queued_resource 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_queued_resource + ] = mock_rpc + + request = {} + client.get_queued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_queued_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_queued_resource_rest_required_fields( + request_type=cloud_tpu.GetQueuedResourceRequest, +): + transport_class = transports.TpuRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_queued_resource._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_queued_resource._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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_tpu.QueuedResource() + # 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_tpu.QueuedResource.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_queued_resource(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_queued_resource_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_queued_resource._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_queued_resource_rest_flattened(): + client = TpuClient( + 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 = cloud_tpu.QueuedResource() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/queuedResources/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_tpu.QueuedResource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_queued_resource(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/queuedResources/*}" + % client.transport._host, + args[1], + ) + + +def test_get_queued_resource_rest_flattened_error(transport: str = "rest"): + client = TpuClient( + 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_queued_resource( + cloud_tpu.GetQueuedResourceRequest(), + name="name_value", + ) + + +def test_create_queued_resource_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 = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_queued_resource + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_queued_resource + ] = mock_rpc + + request = {} + client.create_queued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_queued_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_queued_resource_rest_required_fields( + request_type=cloud_tpu.CreateQueuedResourceRequest, +): + transport_class = transports.TpuRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_queued_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_queued_resource._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "queued_resource_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_queued_resource(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_queued_resource_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_queued_resource._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "queuedResourceId", + "requestId", + ) + ) + & set( + ( + "parent", + "queuedResource", + ) + ) + ) + + +def test_create_queued_resource_rest_flattened(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + queued_resource=cloud_tpu.QueuedResource(name="name_value"), + queued_resource_id="queued_resource_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_queued_resource(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/queuedResources" + % client.transport._host, + args[1], + ) + + +def test_create_queued_resource_rest_flattened_error(transport: str = "rest"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_queued_resource( + cloud_tpu.CreateQueuedResourceRequest(), + parent="parent_value", + queued_resource=cloud_tpu.QueuedResource(name="name_value"), + queued_resource_id="queued_resource_id_value", + ) + + +def test_delete_queued_resource_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 = TpuClient( + 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_queued_resource + 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_queued_resource + ] = mock_rpc + + request = {} + client.delete_queued_resource(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_queued_resource(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_node_rest_required_fields(request_type=cloud_tpu.DeleteNodeRequest): +def test_delete_queued_resource_rest_required_fields( + request_type=cloud_tpu.DeleteQueuedResourceRequest, +): transport_class = transports.TpuRestTransport request_init = {} @@ -6328,7 +9548,7 @@ def test_delete_node_rest_required_fields(request_type=cloud_tpu.DeleteNodeReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_node._get_unset_required_fields(jsonified_request) + ).delete_queued_resource._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -6337,7 +9557,14 @@ def test_delete_node_rest_required_fields(request_type=cloud_tpu.DeleteNodeReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_node._get_unset_required_fields(jsonified_request) + ).delete_queued_resource._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "force", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -6376,23 +9603,31 @@ def test_delete_node_rest_required_fields(request_type=cloud_tpu.DeleteNodeReque req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_node(request) + response = client.delete_queued_resource(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_node_rest_unset_required_fields(): +def test_delete_queued_resource_rest_unset_required_fields(): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_node._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.delete_queued_resource._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "force", + "requestId", + ) + ) + & set(("name",)) + ) -def test_delete_node_rest_flattened(): +def test_delete_queued_resource_rest_flattened(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6404,7 +9639,9 @@ def test_delete_node_rest_flattened(): 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/nodes/sample3"} + sample_request = { + "name": "projects/sample1/locations/sample2/queuedResources/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -6420,19 +9657,20 @@ def test_delete_node_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_node(**mock_args) + client.delete_queued_resource(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=projects/*/locations/*/nodes/*}" % client.transport._host, + "%s/v2/{name=projects/*/locations/*/queuedResources/*}" + % client.transport._host, args[1], ) -def test_delete_node_rest_flattened_error(transport: str = "rest"): +def test_delete_queued_resource_rest_flattened_error(transport: str = "rest"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6441,13 +9679,13 @@ def test_delete_node_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_node( - cloud_tpu.DeleteNodeRequest(), + client.delete_queued_resource( + cloud_tpu.DeleteQueuedResourceRequest(), name="name_value", ) -def test_stop_node_rest_use_cached_wrapped_rpc(): +def test_reset_queued_resource_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: @@ -6461,17 +9699,22 @@ def test_stop_node_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.stop_node in client._transport._wrapped_methods + assert ( + client._transport.reset_queued_resource + 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.stop_node] = mock_rpc + client._transport._wrapped_methods[ + client._transport.reset_queued_resource + ] = mock_rpc request = {} - client.stop_node(request) + client.reset_queued_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6480,14 +9723,16 @@ def test_stop_node_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.stop_node(request) + client.reset_queued_resource(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_stop_node_rest_required_fields(request_type=cloud_tpu.StopNodeRequest): +def test_reset_queued_resource_rest_required_fields( + request_type=cloud_tpu.ResetQueuedResourceRequest, +): transport_class = transports.TpuRestTransport request_init = {} @@ -6502,7 +9747,7 @@ def test_stop_node_rest_required_fields(request_type=cloud_tpu.StopNodeRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).stop_node._get_unset_required_fields(jsonified_request) + ).reset_queued_resource._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -6511,7 +9756,7 @@ def test_stop_node_rest_required_fields(request_type=cloud_tpu.StopNodeRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).stop_node._get_unset_required_fields(jsonified_request) + ).reset_queued_resource._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -6551,23 +9796,81 @@ def test_stop_node_rest_required_fields(request_type=cloud_tpu.StopNodeRequest): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.stop_node(request) + response = client.reset_queued_resource(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_stop_node_rest_unset_required_fields(): +def test_reset_queued_resource_rest_unset_required_fields(): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.stop_node._get_unset_required_fields({}) + unset_fields = transport.reset_queued_resource._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_start_node_rest_use_cached_wrapped_rpc(): +def test_reset_queued_resource_rest_flattened(): + client = TpuClient( + 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/queuedResources/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.reset_queued_resource(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/queuedResources/*}:reset" + % client.transport._host, + args[1], + ) + + +def test_reset_queued_resource_rest_flattened_error(transport: str = "rest"): + client = TpuClient( + 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.reset_queued_resource( + cloud_tpu.ResetQueuedResourceRequest(), + name="name_value", + ) + + +def test_generate_service_identity_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: @@ -6581,37 +9884,40 @@ def test_start_node_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.start_node in client._transport._wrapped_methods + assert ( + client._transport.generate_service_identity + 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.start_node] = mock_rpc + client._transport._wrapped_methods[ + client._transport.generate_service_identity + ] = mock_rpc request = {} - client.start_node(request) + client.generate_service_identity(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.start_node(request) + client.generate_service_identity(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_start_node_rest_required_fields(request_type=cloud_tpu.StartNodeRequest): +def test_generate_service_identity_rest_required_fields( + request_type=cloud_tpu.GenerateServiceIdentityRequest, +): transport_class = transports.TpuRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6622,21 +9928,21 @@ def test_start_node_rest_required_fields(request_type=cloud_tpu.StartNodeRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).start_node._get_unset_required_fields(jsonified_request) + ).generate_service_identity._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" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).start_node._get_unset_required_fields(jsonified_request) + ).generate_service_identity._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6645,7 +9951,7 @@ def test_start_node_rest_required_fields(request_type=cloud_tpu.StartNodeRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = cloud_tpu.GenerateServiceIdentityResponse() # 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 @@ -6665,29 +9971,32 @@ def test_start_node_rest_required_fields(request_type=cloud_tpu.StartNodeRequest response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = cloud_tpu.GenerateServiceIdentityResponse.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.start_node(request) + response = client.generate_service_identity(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_start_node_rest_unset_required_fields(): +def test_generate_service_identity_rest_unset_required_fields(): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.start_node._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.generate_service_identity._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) -def test_update_node_rest_use_cached_wrapped_rpc(): +def test_list_accelerator_types_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: @@ -6701,36 +10010,40 @@ def test_update_node_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_node in client._transport._wrapped_methods + assert ( + client._transport.list_accelerator_types + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_node] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_accelerator_types + ] = mock_rpc request = {} - client.update_node(request) + client.list_accelerator_types(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_node(request) + client.list_accelerator_types(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_node_rest_required_fields(request_type=cloud_tpu.UpdateNodeRequest): +def test_list_accelerator_types_rest_required_fields( + request_type=cloud_tpu.ListAcceleratorTypesRequest, +): transport_class = transports.TpuRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6741,19 +10054,30 @@ def test_update_node_rest_required_fields(request_type=cloud_tpu.UpdateNodeReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_node._get_unset_required_fields(jsonified_request) + ).list_accelerator_types._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_node._get_unset_required_fields(jsonified_request) + ).list_accelerator_types._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6762,7 +10086,7 @@ def test_update_node_rest_required_fields(request_type=cloud_tpu.UpdateNodeReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = cloud_tpu.ListAcceleratorTypesResponse() # 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 @@ -6774,45 +10098,49 @@ def test_update_node_rest_required_fields(request_type=cloud_tpu.UpdateNodeReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = cloud_tpu.ListAcceleratorTypesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_node(request) + response = client.list_accelerator_types(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_node_rest_unset_required_fields(): +def test_list_accelerator_types_rest_unset_required_fields(): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_node._get_unset_required_fields({}) + unset_fields = transport.list_accelerator_types._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("updateMask",)) - & set( + set( ( - "updateMask", - "node", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) -def test_update_node_rest_flattened(): +def test_list_accelerator_types_rest_flattened(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6821,41 +10149,41 @@ def test_update_node_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = cloud_tpu.ListAcceleratorTypesResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "node": {"name": "projects/sample1/locations/sample2/nodes/sample3"} - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - node=cloud_tpu.Node(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_tpu.ListAcceleratorTypesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_node(**mock_args) + client.list_accelerator_types(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{node.name=projects/*/locations/*/nodes/*}" % client.transport._host, + "%s/v2/{parent=projects/*/locations/*}/acceleratorTypes" + % client.transport._host, args[1], ) -def test_update_node_rest_flattened_error(transport: str = "rest"): +def test_list_accelerator_types_rest_flattened_error(transport: str = "rest"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6864,14 +10192,76 @@ def test_update_node_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_node( - cloud_tpu.UpdateNodeRequest(), - node=cloud_tpu.Node(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_accelerator_types( + cloud_tpu.ListAcceleratorTypesRequest(), + parent="parent_value", ) -def test_generate_service_identity_rest_use_cached_wrapped_rpc(): +def test_list_accelerator_types_rest_pager(transport: str = "rest"): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + ], + next_page_token="abc", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[], + next_page_token="def", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + ], + next_page_token="ghi", + ), + cloud_tpu.ListAcceleratorTypesResponse( + accelerator_types=[ + cloud_tpu.AcceleratorType(), + cloud_tpu.AcceleratorType(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_tpu.ListAcceleratorTypesResponse.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_accelerator_types(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_tpu.AcceleratorType) for i in results) + + pages = list(client.list_accelerator_types(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_accelerator_type_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: @@ -6886,8 +10276,7 @@ def test_generate_service_identity_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.generate_service_identity - in client._transport._wrapped_methods + client._transport.get_accelerator_type in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6896,29 +10285,29 @@ def test_generate_service_identity_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.generate_service_identity + client._transport.get_accelerator_type ] = mock_rpc request = {} - client.generate_service_identity(request) + client.get_accelerator_type(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.generate_service_identity(request) + client.get_accelerator_type(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_generate_service_identity_rest_required_fields( - request_type=cloud_tpu.GenerateServiceIdentityRequest, +def test_get_accelerator_type_rest_required_fields( + request_type=cloud_tpu.GetAcceleratorTypeRequest, ): transport_class = transports.TpuRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6929,21 +10318,21 @@ def test_generate_service_identity_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).generate_service_identity._get_unset_required_fields(jsonified_request) + ).get_accelerator_type._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).generate_service_identity._get_unset_required_fields(jsonified_request) + ).get_accelerator_type._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6952,7 +10341,7 @@ def test_generate_service_identity_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = cloud_tpu.GenerateServiceIdentityResponse() + return_value = cloud_tpu.AcceleratorType() # 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 @@ -6964,40 +10353,99 @@ def test_generate_service_identity_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = cloud_tpu.GenerateServiceIdentityResponse.pb(return_value) + return_value = cloud_tpu.AcceleratorType.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.generate_service_identity(request) + response = client.get_accelerator_type(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_generate_service_identity_rest_unset_required_fields(): +def test_get_accelerator_type_rest_unset_required_fields(): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.generate_service_identity._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent",))) + unset_fields = transport.get_accelerator_type._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_accelerator_type_rest_flattened(): + client = TpuClient( + 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 = cloud_tpu.AcceleratorType() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/acceleratorTypes/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_tpu.AcceleratorType.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_accelerator_type(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/acceleratorTypes/*}" + % client.transport._host, + args[1], + ) + + +def test_get_accelerator_type_rest_flattened_error(transport: str = "rest"): + client = TpuClient( + 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_accelerator_type( + cloud_tpu.GetAcceleratorTypeRequest(), + name="name_value", + ) -def test_list_accelerator_types_rest_use_cached_wrapped_rpc(): +def test_list_runtime_versions_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: @@ -7012,7 +10460,7 @@ def test_list_accelerator_types_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_accelerator_types + client._transport.list_runtime_versions in client._transport._wrapped_methods ) @@ -7022,24 +10470,24 @@ def test_list_accelerator_types_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_accelerator_types + client._transport.list_runtime_versions ] = mock_rpc request = {} - client.list_accelerator_types(request) + client.list_runtime_versions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_accelerator_types(request) + client.list_runtime_versions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_accelerator_types_rest_required_fields( - request_type=cloud_tpu.ListAcceleratorTypesRequest, +def test_list_runtime_versions_rest_required_fields( + request_type=cloud_tpu.ListRuntimeVersionsRequest, ): transport_class = transports.TpuRestTransport @@ -7055,7 +10503,7 @@ def test_list_accelerator_types_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_accelerator_types._get_unset_required_fields(jsonified_request) + ).list_runtime_versions._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -7064,7 +10512,7 @@ def test_list_accelerator_types_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_accelerator_types._get_unset_required_fields(jsonified_request) + ).list_runtime_versions._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( @@ -7087,7 +10535,7 @@ def test_list_accelerator_types_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = cloud_tpu.ListAcceleratorTypesResponse() + return_value = cloud_tpu.ListRuntimeVersionsResponse() # 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 @@ -7108,26 +10556,26 @@ def test_list_accelerator_types_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = cloud_tpu.ListAcceleratorTypesResponse.pb(return_value) + return_value = cloud_tpu.ListRuntimeVersionsResponse.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_accelerator_types(request) + response = client.list_runtime_versions(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_accelerator_types_rest_unset_required_fields(): +def test_list_runtime_versions_rest_unset_required_fields(): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_accelerator_types._get_unset_required_fields({}) + unset_fields = transport.list_runtime_versions._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( @@ -7141,7 +10589,7 @@ def test_list_accelerator_types_rest_unset_required_fields(): ) -def test_list_accelerator_types_rest_flattened(): +def test_list_runtime_versions_rest_flattened(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7150,7 +10598,7 @@ def test_list_accelerator_types_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = cloud_tpu.ListAcceleratorTypesResponse() + return_value = cloud_tpu.ListRuntimeVersionsResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "projects/sample1/locations/sample2"} @@ -7165,26 +10613,26 @@ def test_list_accelerator_types_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = cloud_tpu.ListAcceleratorTypesResponse.pb(return_value) + return_value = cloud_tpu.ListRuntimeVersionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_accelerator_types(**mock_args) + client.list_runtime_versions(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=projects/*/locations/*}/acceleratorTypes" + "%s/v2/{parent=projects/*/locations/*}/runtimeVersions" % client.transport._host, args[1], ) -def test_list_accelerator_types_rest_flattened_error(transport: str = "rest"): +def test_list_runtime_versions_rest_flattened_error(transport: str = "rest"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7193,13 +10641,13 @@ def test_list_accelerator_types_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_accelerator_types( - cloud_tpu.ListAcceleratorTypesRequest(), + client.list_runtime_versions( + cloud_tpu.ListRuntimeVersionsRequest(), parent="parent_value", ) -def test_list_accelerator_types_rest_pager(transport: str = "rest"): +def test_list_runtime_versions_rest_pager(transport: str = "rest"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7211,28 +10659,28 @@ def test_list_accelerator_types_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), ], next_page_token="abc", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[], + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[], next_page_token="def", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), ], next_page_token="ghi", ), - cloud_tpu.ListAcceleratorTypesResponse( - accelerator_types=[ - cloud_tpu.AcceleratorType(), - cloud_tpu.AcceleratorType(), + cloud_tpu.ListRuntimeVersionsResponse( + runtime_versions=[ + cloud_tpu.RuntimeVersion(), + cloud_tpu.RuntimeVersion(), ], ), ) @@ -7241,7 +10689,7 @@ def test_list_accelerator_types_rest_pager(transport: str = "rest"): # Wrap the values into proper Response objs response = tuple( - cloud_tpu.ListAcceleratorTypesResponse.to_json(x) for x in response + cloud_tpu.ListRuntimeVersionsResponse.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): @@ -7251,18 +10699,18 @@ def test_list_accelerator_types_rest_pager(transport: str = "rest"): sample_request = {"parent": "projects/sample1/locations/sample2"} - pager = client.list_accelerator_types(request=sample_request) + pager = client.list_runtime_versions(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, cloud_tpu.AcceleratorType) for i in results) + assert all(isinstance(i, cloud_tpu.RuntimeVersion) for i in results) - pages = list(client.list_accelerator_types(request=sample_request).pages) + pages = list(client.list_runtime_versions(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_accelerator_type_rest_use_cached_wrapped_rpc(): +def test_get_runtime_version_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: @@ -7277,7 +10725,7 @@ def test_get_accelerator_type_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_accelerator_type in client._transport._wrapped_methods + client._transport.get_runtime_version in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -7286,24 +10734,24 @@ def test_get_accelerator_type_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_accelerator_type + client._transport.get_runtime_version ] = mock_rpc request = {} - client.get_accelerator_type(request) + client.get_runtime_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_accelerator_type(request) + client.get_runtime_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_accelerator_type_rest_required_fields( - request_type=cloud_tpu.GetAcceleratorTypeRequest, +def test_get_runtime_version_rest_required_fields( + request_type=cloud_tpu.GetRuntimeVersionRequest, ): transport_class = transports.TpuRestTransport @@ -7319,7 +10767,7 @@ def test_get_accelerator_type_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_accelerator_type._get_unset_required_fields(jsonified_request) + ).get_runtime_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -7328,7 +10776,7 @@ def test_get_accelerator_type_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_accelerator_type._get_unset_required_fields(jsonified_request) + ).get_runtime_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -7342,7 +10790,7 @@ def test_get_accelerator_type_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = cloud_tpu.AcceleratorType() + return_value = cloud_tpu.RuntimeVersion() # 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 @@ -7363,30 +10811,30 @@ def test_get_accelerator_type_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = cloud_tpu.AcceleratorType.pb(return_value) + return_value = cloud_tpu.RuntimeVersion.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_accelerator_type(request) + response = client.get_runtime_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_accelerator_type_rest_unset_required_fields(): +def test_get_runtime_version_rest_unset_required_fields(): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_accelerator_type._get_unset_required_fields({}) + unset_fields = transport.get_runtime_version._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_accelerator_type_rest_flattened(): +def test_get_runtime_version_rest_flattened(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7395,11 +10843,11 @@ def test_get_accelerator_type_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = cloud_tpu.AcceleratorType() + return_value = cloud_tpu.RuntimeVersion() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/acceleratorTypes/sample3" + "name": "projects/sample1/locations/sample2/runtimeVersions/sample3" } # get truthy value for each flattened field @@ -7412,26 +10860,26 @@ def test_get_accelerator_type_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = cloud_tpu.AcceleratorType.pb(return_value) + return_value = cloud_tpu.RuntimeVersion.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_accelerator_type(**mock_args) + client.get_runtime_version(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=projects/*/locations/*/acceleratorTypes/*}" + "%s/v2/{name=projects/*/locations/*/runtimeVersions/*}" % client.transport._host, args[1], ) -def test_get_accelerator_type_rest_flattened_error(transport: str = "rest"): +def test_get_runtime_version_rest_flattened_error(transport: str = "rest"): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7440,13 +10888,13 @@ def test_get_accelerator_type_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_accelerator_type( - cloud_tpu.GetAcceleratorTypeRequest(), + client.get_runtime_version( + cloud_tpu.GetRuntimeVersionRequest(), name="name_value", ) -def test_list_runtime_versions_rest_use_cached_wrapped_rpc(): +def test_get_guest_attributes_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: @@ -7461,8 +10909,7 @@ def test_list_runtime_versions_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_runtime_versions - in client._transport._wrapped_methods + client._transport.get_guest_attributes in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -7471,29 +10918,29 @@ def test_list_runtime_versions_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_runtime_versions + client._transport.get_guest_attributes ] = mock_rpc request = {} - client.list_runtime_versions(request) + client.get_guest_attributes(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_runtime_versions(request) + client.get_guest_attributes(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_runtime_versions_rest_required_fields( - request_type=cloud_tpu.ListRuntimeVersionsRequest, +def test_get_guest_attributes_rest_required_fields( + request_type=cloud_tpu.GetGuestAttributesRequest, ): transport_class = transports.TpuRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7504,30 +10951,21 @@ def test_list_runtime_versions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_runtime_versions._get_unset_required_fields(jsonified_request) + ).get_guest_attributes._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_runtime_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) + ).get_guest_attributes._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7536,7 +10974,7 @@ def test_list_runtime_versions_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = cloud_tpu.ListRuntimeVersionsResponse() + return_value = cloud_tpu.GetGuestAttributesResponse() # 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 @@ -7548,745 +10986,910 @@ def test_list_runtime_versions_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = cloud_tpu.ListRuntimeVersionsResponse.pb(return_value) + return_value = cloud_tpu.GetGuestAttributesResponse.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_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_guest_attributes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_guest_attributes_rest_unset_required_fields(): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_guest_attributes._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TpuGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TpuGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TpuClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TpuGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TpuClient( + 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 = TpuClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TpuGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TpuClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TpuGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TpuClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TpuGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TpuGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel - response = client.list_runtime_versions(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.parametrize( + "transport_class", + [ + transports.TpuGrpcTransport, + transports.TpuGrpcAsyncIOTransport, + transports.TpuRestTransport, + ], +) +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_list_runtime_versions_rest_unset_required_fields(): - transport = transports.TpuRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_transport_kind_grpc(): + transport = TpuClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) + assert transport.kind == "grpc" - unset_fields = transport.list_runtime_versions._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) + +def test_initialize_client_w_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) + assert client is not None -def test_list_runtime_versions_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_list_nodes_empty_call_grpc(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = cloud_tpu.ListRuntimeVersionsResponse() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_nodes), "__call__") as call: + call.return_value = cloud_tpu.ListNodesResponse() + client.list_nodes(request=None) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.ListNodesRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + assert args[0] == request_msg - # 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_tpu.ListRuntimeVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_runtime_versions(**mock_args) +# 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_node_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*/locations/*}/runtimeVersions" - % client.transport._host, - args[1], - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_node), "__call__") as call: + call.return_value = cloud_tpu.Node() + client.get_node(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.GetNodeRequest() + assert args[0] == request_msg -def test_list_runtime_versions_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_create_node_empty_call_grpc(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_runtime_versions( - cloud_tpu.ListRuntimeVersionsRequest(), - parent="parent_value", - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_node), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_node(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.CreateNodeRequest() + assert args[0] == request_msg -def test_list_runtime_versions_rest_pager(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_node_empty_call_grpc(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # 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_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - ], - next_page_token="abc", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[], - next_page_token="def", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - ], - next_page_token="ghi", - ), - cloud_tpu.ListRuntimeVersionsResponse( - runtime_versions=[ - cloud_tpu.RuntimeVersion(), - cloud_tpu.RuntimeVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_node), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_node(request=None) - # Wrap the values into proper Response objs - response = tuple( - cloud_tpu.ListRuntimeVersionsResponse.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 underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.DeleteNodeRequest() - sample_request = {"parent": "projects/sample1/locations/sample2"} + assert args[0] == request_msg - pager = client.list_runtime_versions(request=sample_request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, cloud_tpu.RuntimeVersion) for i in results) +# 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_stop_node_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.list_runtime_versions(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, and fake the request. + with mock.patch.object(type(client.transport.stop_node), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.stop_node(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.StopNodeRequest() -def test_get_runtime_version_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 = TpuClient( - 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.get_runtime_version in client._transport._wrapped_methods - ) +# 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_start_node_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # 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_runtime_version - ] = mock_rpc + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_node), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.start_node(request=None) - request = {} - client.get_runtime_version(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.StartNodeRequest() - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + assert args[0] == request_msg - client.get_runtime_version(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_node_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_node), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_node(request=None) -def test_get_runtime_version_rest_required_fields( - request_type=cloud_tpu.GetRuntimeVersionRequest, -): - transport_class = transports.TpuRestTransport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.UpdateNodeRequest() - 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) - ) + assert args[0] == request_msg - # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_runtime_version._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_queued_resources_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # 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_queued_resources), "__call__" + ) as call: + call.return_value = cloud_tpu.ListQueuedResourcesResponse() + client.list_queued_resources(request=None) - jsonified_request["name"] = "name_value" + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.ListQueuedResourcesRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_runtime_version._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" +# 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_queued_resource_empty_call_grpc(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = cloud_tpu.RuntimeVersion() - # 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 + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_queued_resource), "__call__" + ) as call: + call.return_value = cloud_tpu.QueuedResource() + client.get_queued_resource(request=None) - # Convert return value to protobuf type - return_value = cloud_tpu.RuntimeVersion.pb(return_value) - 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_tpu.GetQueuedResourceRequest() - 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.get_runtime_version(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_queued_resource_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_queued_resource), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_queued_resource(request=None) -def test_get_runtime_version_rest_unset_required_fields(): - transport = transports.TpuRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.CreateQueuedResourceRequest() - unset_fields = transport.get_runtime_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert args[0] == request_msg -def test_get_runtime_version_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_delete_queued_resource_empty_call_grpc(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = cloud_tpu.RuntimeVersion() + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_queued_resource), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_queued_resource(request=None) - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/runtimeVersions/sample3" - } + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.DeleteQueuedResourceRequest() - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + assert args[0] == request_msg - # 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_tpu.RuntimeVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_runtime_version(**mock_args) +# 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_reset_queued_resource_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{name=projects/*/locations/*/runtimeVersions/*}" - % client.transport._host, - args[1], - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reset_queued_resource), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.reset_queued_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.ResetQueuedResourceRequest() + + assert args[0] == request_msg -def test_get_runtime_version_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_generate_service_identity_empty_call_grpc(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_runtime_version( - cloud_tpu.GetRuntimeVersionRequest(), - name="name_value", - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_service_identity), "__call__" + ) as call: + call.return_value = cloud_tpu.GenerateServiceIdentityResponse() + client.generate_service_identity(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.GenerateServiceIdentityRequest() -def test_get_guest_attributes_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 = TpuClient( - 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.get_guest_attributes in client._transport._wrapped_methods - ) +# 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_accelerator_types_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # 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_guest_attributes - ] = mock_rpc + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_accelerator_types), "__call__" + ) as call: + call.return_value = cloud_tpu.ListAcceleratorTypesResponse() + client.list_accelerator_types(request=None) - request = {} - client.get_guest_attributes(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.ListAcceleratorTypesRequest() - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + assert args[0] == request_msg - client.get_guest_attributes(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_accelerator_type_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_accelerator_type), "__call__" + ) as call: + call.return_value = cloud_tpu.AcceleratorType() + client.get_accelerator_type(request=None) -def test_get_guest_attributes_rest_required_fields( - request_type=cloud_tpu.GetGuestAttributesRequest, -): - transport_class = transports.TpuRestTransport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.GetAcceleratorTypeRequest() - 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) - ) + assert args[0] == request_msg - # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_guest_attributes._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_runtime_versions_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # 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_runtime_versions), "__call__" + ) as call: + call.return_value = cloud_tpu.ListRuntimeVersionsResponse() + client.list_runtime_versions(request=None) - jsonified_request["name"] = "name_value" + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.ListRuntimeVersionsRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_guest_attributes._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" +# 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_runtime_version_empty_call_grpc(): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = cloud_tpu.GetGuestAttributesResponse() - # 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_runtime_version), "__call__" + ) as call: + call.return_value = cloud_tpu.RuntimeVersion() + client.get_runtime_version(request=None) - response_value = Response() - response_value.status_code = 200 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.GetRuntimeVersionRequest() - # Convert return value to protobuf type - return_value = cloud_tpu.GetGuestAttributesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + assert args[0] == request_msg - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_guest_attributes(request) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_guest_attributes_empty_call_grpc(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_guest_attributes), "__call__" + ) as call: + call.return_value = cloud_tpu.GetGuestAttributesResponse() + client.get_guest_attributes(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.GetGuestAttributesRequest() -def test_get_guest_attributes_rest_unset_required_fields(): - transport = transports.TpuRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + assert args[0] == request_msg - unset_fields = transport.get_guest_attributes._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + +def test_transport_kind_grpc_asyncio(): + transport = TpuAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TpuGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +def test_initialize_client_w_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) - with pytest.raises(ValueError): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + assert client is not None - # It is an error to provide a credentials file and a transport instance. - transport = transports.TpuGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + +# 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_nodes_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - with pytest.raises(ValueError): - client = TpuClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_nodes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.ListNodesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) + await client.list_nodes(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.TpuGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.ListNodesRequest() + + 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_node_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TpuClient( - 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 = TpuClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_node), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.Node( + name="name_value", + description="description_value", + accelerator_type="accelerator_type_value", + state=cloud_tpu.Node.State.CREATING, + health_description="health_description_value", + runtime_version="runtime_version_value", + cidr_block="cidr_block_value", + health=cloud_tpu.Node.Health.HEALTHY, + tags=["tags_value"], + id=205, + api_version=cloud_tpu.Node.ApiVersion.V1_ALPHA1, + queued_resource="queued_resource_value", + multislice_node=True, + ) ) + await client.get_node(request=None) - # It is an error to provide scopes and a transport instance. - transport = transports.TpuGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TpuClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.GetNodeRequest() + + 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_node_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_node), "__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_node(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.CreateNodeRequest() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TpuGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TpuClient(transport=transport) - assert client.transport is transport + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TpuGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +# 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_node_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - channel = transport.grpc_channel - assert channel - transport = transports.TpuGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_node), "__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_node(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.DeleteNodeRequest() -@pytest.mark.parametrize( - "transport_class", - [ - transports.TpuGrpcTransport, - transports.TpuGrpcAsyncIOTransport, - transports.TpuRestTransport, - ], -) -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() + assert args[0] == request_msg -def test_transport_kind_grpc(): - transport = TpuClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() +# 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_stop_node_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert transport.kind == "grpc" + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.stop_node), "__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.stop_node(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.StopNodeRequest() -def test_initialize_client_w_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_list_nodes_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_start_node_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_nodes), "__call__") as call: - call.return_value = cloud_tpu.ListNodesResponse() - client.list_nodes(request=None) + with mock.patch.object(type(client.transport.start_node), "__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.start_node(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.ListNodesRequest() + request_msg = cloud_tpu.StartNodeRequest() 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_node_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_update_node_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_node), "__call__") as call: - call.return_value = cloud_tpu.Node() - client.get_node(request=None) + with mock.patch.object(type(client.transport.update_node), "__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_node(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.GetNodeRequest() + request_msg = cloud_tpu.UpdateNodeRequest() 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_node_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_queued_resources_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_node), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_node(request=None) + with mock.patch.object( + type(client.transport.list_queued_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.ListQueuedResourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_queued_resources(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.CreateNodeRequest() + request_msg = cloud_tpu.ListQueuedResourcesRequest() 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_node_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_queued_resource_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_node), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_node(request=None) + with mock.patch.object( + type(client.transport.get_queued_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.QueuedResource( + name="name_value", + reservation_name="reservation_name_value", + ) + ) + await client.get_queued_resource(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.DeleteNodeRequest() + request_msg = cloud_tpu.GetQueuedResourceRequest() 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_stop_node_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_create_queued_resource_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.stop_node), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.stop_node(request=None) + with mock.patch.object( + type(client.transport.create_queued_resource), "__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_queued_resource(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.StopNodeRequest() + request_msg = cloud_tpu.CreateQueuedResourceRequest() 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_start_node_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_delete_queued_resource_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.start_node), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.start_node(request=None) + with mock.patch.object( + type(client.transport.delete_queued_resource), "__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_queued_resource(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.StartNodeRequest() + request_msg = cloud_tpu.DeleteQueuedResourceRequest() 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_node_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_reset_queued_resource_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_node), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_node(request=None) + with mock.patch.object( + type(client.transport.reset_queued_resource), "__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.reset_queued_resource(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.UpdateNodeRequest() + request_msg = cloud_tpu.ResetQueuedResourceRequest() 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_generate_service_identity_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_generate_service_identity_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.generate_service_identity), "__call__" ) as call: - call.return_value = cloud_tpu.GenerateServiceIdentityResponse() - client.generate_service_identity(request=None) + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.GenerateServiceIdentityResponse() + ) + await client.generate_service_identity(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -8298,18 +11901,25 @@ def test_generate_service_identity_empty_call_grpc(): # 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_accelerator_types_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_accelerator_types_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.list_accelerator_types), "__call__" ) as call: - call.return_value = cloud_tpu.ListAcceleratorTypesResponse() - client.list_accelerator_types(request=None) + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.ListAcceleratorTypesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_accelerator_types(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -8321,18 +11931,25 @@ def test_list_accelerator_types_empty_call_grpc(): # 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_accelerator_type_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_accelerator_type_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.get_accelerator_type), "__call__" ) as call: - call.return_value = cloud_tpu.AcceleratorType() - client.get_accelerator_type(request=None) + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.AcceleratorType( + name="name_value", + type_="type__value", + ) + ) + await client.get_accelerator_type(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -8344,18 +11961,25 @@ def test_get_accelerator_type_empty_call_grpc(): # 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_runtime_versions_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_runtime_versions_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.list_runtime_versions), "__call__" ) as call: - call.return_value = cloud_tpu.ListRuntimeVersionsResponse() - client.list_runtime_versions(request=None) + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.ListRuntimeVersionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_runtime_versions(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -8367,18 +11991,25 @@ def test_list_runtime_versions_empty_call_grpc(): # 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_runtime_version_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_runtime_version_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.get_runtime_version), "__call__" ) as call: - call.return_value = cloud_tpu.RuntimeVersion() - client.get_runtime_version(request=None) + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.RuntimeVersion( + name="name_value", + version="version_value", + ) + ) + await client.get_runtime_version(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -8390,18 +12021,22 @@ def test_get_runtime_version_empty_call_grpc(): # 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_guest_attributes_empty_call_grpc(): - client = TpuClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_guest_attributes_empty_call_grpc_asyncio(): + client = TpuAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.get_guest_attributes), "__call__" ) as call: - call.return_value = cloud_tpu.GetGuestAttributesResponse() - client.get_guest_attributes(request=None) + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_tpu.GetGuestAttributesResponse() + ) + await client.get_guest_attributes(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -8411,399 +12046,619 @@ def test_get_guest_attributes_empty_call_grpc(): assert args[0] == request_msg -def test_transport_kind_grpc_asyncio(): - transport = TpuAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() +def test_transport_kind_rest(): + transport = TpuClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == "grpc_asyncio" + assert transport.kind == "rest" -def test_initialize_client_w_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" +def test_list_nodes_rest_bad_request(request_type=cloud_tpu.ListNodesRequest): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - assert client is not None + # 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_nodes(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_nodes_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.ListNodesRequest, + dict, + ], +) +def test_list_nodes_rest_call_success(request_type): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_nodes), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.ListNodesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + # 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_tpu.ListNodesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - await client.list_nodes(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.ListNodesRequest() + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = cloud_tpu.ListNodesResponse.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_nodes(request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNodesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_node_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_nodes_rest_interceptors(null_interceptor): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TpuRestInterceptor(), ) + client = TpuClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_node), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.Node( - name="name_value", - description="description_value", - accelerator_type="accelerator_type_value", - state=cloud_tpu.Node.State.CREATING, - health_description="health_description_value", - runtime_version="runtime_version_value", - cidr_block="cidr_block_value", - health=cloud_tpu.Node.Health.HEALTHY, - tags=["tags_value"], - id=205, - api_version=cloud_tpu.Node.ApiVersion.V1_ALPHA1, - queued_resource="queued_resource_value", - multislice_node=True, - ) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.TpuRestInterceptor, "post_list_nodes" + ) as post, mock.patch.object( + transports.TpuRestInterceptor, "pre_list_nodes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_tpu.ListNodesRequest.pb(cloud_tpu.ListNodesRequest()) + 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_tpu.ListNodesResponse.to_json( + cloud_tpu.ListNodesResponse() ) - await client.get_node(request=None) + req.return_value.content = return_value - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.GetNodeRequest() + request = cloud_tpu.ListNodesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_tpu.ListNodesResponse() + + client.list_nodes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_node_rest_bad_request(request_type=cloud_tpu.GetNodeRequest): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/nodes/sample3"} + request = request_type(**request_init) - assert args[0] == request_msg + # 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_node(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_create_node_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.GetNodeRequest, + dict, + ], +) +def test_get_node_rest_call_success(request_type): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_node), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/nodes/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_tpu.Node( + name="name_value", + description="description_value", + accelerator_type="accelerator_type_value", + state=cloud_tpu.Node.State.CREATING, + health_description="health_description_value", + runtime_version="runtime_version_value", + cidr_block="cidr_block_value", + health=cloud_tpu.Node.Health.HEALTHY, + tags=["tags_value"], + id=205, + api_version=cloud_tpu.Node.ApiVersion.V1_ALPHA1, + queued_resource="queued_resource_value", + multislice_node=True, ) - await client.create_node(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.CreateNodeRequest() + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = cloud_tpu.Node.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_node(request) + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_tpu.Node) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.accelerator_type == "accelerator_type_value" + assert response.state == cloud_tpu.Node.State.CREATING + assert response.health_description == "health_description_value" + assert response.runtime_version == "runtime_version_value" + assert response.cidr_block == "cidr_block_value" + assert response.health == cloud_tpu.Node.Health.HEALTHY + assert response.tags == ["tags_value"] + assert response.id == 205 + assert response.api_version == cloud_tpu.Node.ApiVersion.V1_ALPHA1 + assert response.queued_resource == "queued_resource_value" + assert response.multislice_node is True -# 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_node_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_node_rest_interceptors(null_interceptor): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TpuRestInterceptor(), ) + client = TpuClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_node), "__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_node(request=None) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.TpuRestInterceptor, "post_get_node" + ) as post, mock.patch.object( + transports.TpuRestInterceptor, "pre_get_node" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_tpu.GetNodeRequest.pb(cloud_tpu.GetNodeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.DeleteNodeRequest() + 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_tpu.Node.to_json(cloud_tpu.Node()) + req.return_value.content = return_value - assert args[0] == request_msg + request = cloud_tpu.GetNodeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_tpu.Node() + client.get_node( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -# 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_stop_node_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + pre.assert_called_once() + post.assert_called_once() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.stop_node), "__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.stop_node(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.StopNodeRequest() +def test_create_node_rest_bad_request(request_type=cloud_tpu.CreateNodeRequest): + client = TpuClient( + 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) - assert args[0] == request_msg + # 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_node(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_start_node_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.CreateNodeRequest, + dict, + ], +) +def test_create_node_rest_call_success(request_type): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.start_node), "__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.start_node(request=None) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["node"] = { + "name": "name_value", + "description": "description_value", + "accelerator_type": "accelerator_type_value", + "state": 1, + "health_description": "health_description_value", + "runtime_version": "runtime_version_value", + "network_config": { + "network": "network_value", + "subnetwork": "subnetwork_value", + "enable_external_ips": True, + "can_ip_forward": True, + "queue_count": 1197, + }, + "network_configs": {}, + "cidr_block": "cidr_block_value", + "service_account": { + "email": "email_value", + "scope": ["scope_value1", "scope_value2"], + }, + "create_time": {"seconds": 751, "nanos": 543}, + "scheduling_config": {"preemptible": True, "reserved": True, "spot": True}, + "network_endpoints": [ + { + "ip_address": "ip_address_value", + "port": 453, + "access_config": {"external_ip": "external_ip_value"}, + } + ], + "health": 1, + "labels": {}, + "metadata": {}, + "tags": ["tags_value1", "tags_value2"], + "id": 205, + "data_disks": [{"source_disk": "source_disk_value", "mode": 1}], + "api_version": 1, + "symptoms": [ + { + "create_time": {}, + "symptom_type": 1, + "details": "details_value", + "worker_id": "worker_id_value", + } + ], + "shielded_instance_config": {"enable_secure_boot": True}, + "accelerator_config": {"type_": 2, "topology": "topology_value"}, + "queued_resource": "queued_resource_value", + "multislice_node": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.StartNodeRequest() + # Determine if the message type is proto-plus or protobuf + test_field = cloud_tpu.CreateNodeRequest.meta.fields["node"] - assert args[0] == request_msg + 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") -# 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_node_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + 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 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_node), "__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_node(request=None) + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.UpdateNodeRequest() + subfields_not_in_runtime = [] - assert args[0] == request_msg + # 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["node"].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, + } + ) -# 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_generate_service_identity_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # 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["node"][field])): + del request_init["node"][field][i][subfield] + else: + del request_init["node"][field][subfield] + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_service_identity), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.GenerateServiceIdentityResponse() - ) - await client.generate_service_identity(request=None) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.GenerateServiceIdentityRequest() + # 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_node(request) - assert args[0] == request_msg + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_accelerator_types_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_node_rest_interceptors(null_interceptor): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TpuRestInterceptor(), ) + client = TpuClient(transport=transport) - # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_accelerator_types), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.ListAcceleratorTypesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_accelerator_types(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.ListAcceleratorTypesRequest() - - assert args[0] == request_msg + 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.TpuRestInterceptor, "post_create_node" + ) as post, mock.patch.object( + transports.TpuRestInterceptor, "pre_create_node" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_tpu.CreateNodeRequest.pb(cloud_tpu.CreateNodeRequest()) + 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 -# 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_accelerator_type_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + request = cloud_tpu.CreateNodeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_accelerator_type), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.AcceleratorType( - name="name_value", - type_="type__value", - ) + client.create_node( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - await client.get_accelerator_type(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.GetAcceleratorTypeRequest() - assert args[0] == request_msg + pre.assert_called_once() + post.assert_called_once() -# 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_runtime_versions_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_node_rest_bad_request(request_type=cloud_tpu.DeleteNodeRequest): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/nodes/sample3"} + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_runtime_versions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.ListRuntimeVersionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_runtime_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.ListRuntimeVersionsRequest() - - assert args[0] == request_msg + # 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_node(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_get_runtime_version_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.DeleteNodeRequest, + dict, + ], +) +def test_delete_node_rest_call_success(request_type): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_runtime_version), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.RuntimeVersion( - name="name_value", - version="version_value", - ) - ) - await client.get_runtime_version(request=None) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/nodes/sample3"} + request = request_type(**request_init) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.GetRuntimeVersionRequest() + # 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") - assert args[0] == request_msg + # 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_node(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_guest_attributes_empty_call_grpc_asyncio(): - client = TpuAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_node_rest_interceptors(null_interceptor): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TpuRestInterceptor(), ) + client = TpuClient(transport=transport) - # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_guest_attributes), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_tpu.GetGuestAttributesResponse() - ) - await client.get_guest_attributes(request=None) + 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.TpuRestInterceptor, "post_delete_node" + ) as post, mock.patch.object( + transports.TpuRestInterceptor, "pre_delete_node" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_tpu.DeleteNodeRequest.pb(cloud_tpu.DeleteNodeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = cloud_tpu.GetGuestAttributesRequest() + 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 - assert args[0] == request_msg + request = cloud_tpu.DeleteNodeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + client.delete_node( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = TpuClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() -def test_list_nodes_rest_bad_request(request_type=cloud_tpu.ListNodesRequest): +def test_stop_node_rest_bad_request(request_type=cloud_tpu.StopNodeRequest): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/nodes/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -8818,53 +12673,45 @@ def test_list_nodes_rest_bad_request(request_type=cloud_tpu.ListNodesRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_nodes(request) + client.stop_node(request) @pytest.mark.parametrize( "request_type", [ - cloud_tpu.ListNodesRequest, + cloud_tpu.StopNodeRequest, dict, ], ) -def test_list_nodes_rest_call_success(request_type): +def test_stop_node_rest_call_success(request_type): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/nodes/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_tpu.ListNodesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = cloud_tpu.ListNodesResponse.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_nodes(request) + response = client.stop_node(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNodesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_nodes_rest_interceptors(null_interceptor): +def test_stop_node_rest_interceptors(null_interceptor): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.TpuRestInterceptor(), @@ -8876,13 +12723,15 @@ def test_list_nodes_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.TpuRestInterceptor, "post_list_nodes" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TpuRestInterceptor, "post_stop_node" ) as post, mock.patch.object( - transports.TpuRestInterceptor, "pre_list_nodes" + transports.TpuRestInterceptor, "pre_stop_node" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_tpu.ListNodesRequest.pb(cloud_tpu.ListNodesRequest()) + pb_message = cloud_tpu.StopNodeRequest.pb(cloud_tpu.StopNodeRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8893,20 +12742,18 @@ def test_list_nodes_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = cloud_tpu.ListNodesResponse.to_json( - cloud_tpu.ListNodesResponse() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = cloud_tpu.ListNodesRequest() + request = cloud_tpu.StopNodeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = cloud_tpu.ListNodesResponse() + post.return_value = operations_pb2.Operation() - client.list_nodes( + client.stop_node( request, metadata=[ ("key", "val"), @@ -8918,7 +12765,7 @@ def test_list_nodes_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_node_rest_bad_request(request_type=cloud_tpu.GetNodeRequest): +def test_start_node_rest_bad_request(request_type=cloud_tpu.StartNodeRequest): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8938,17 +12785,17 @@ def test_get_node_rest_bad_request(request_type=cloud_tpu.GetNodeRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_node(request) + client.start_node(request) @pytest.mark.parametrize( "request_type", [ - cloud_tpu.GetNodeRequest, + cloud_tpu.StartNodeRequest, dict, ], ) -def test_get_node_rest_call_success(request_type): +def test_start_node_rest_call_success(request_type): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8960,53 +12807,23 @@ def test_get_node_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = cloud_tpu.Node( - name="name_value", - description="description_value", - accelerator_type="accelerator_type_value", - state=cloud_tpu.Node.State.CREATING, - health_description="health_description_value", - runtime_version="runtime_version_value", - cidr_block="cidr_block_value", - health=cloud_tpu.Node.Health.HEALTHY, - tags=["tags_value"], - id=205, - api_version=cloud_tpu.Node.ApiVersion.V1_ALPHA1, - queued_resource="queued_resource_value", - multislice_node=True, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = cloud_tpu.Node.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_node(request) + response = client.start_node(request) # Establish that the response is the type that we expect. - assert isinstance(response, cloud_tpu.Node) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.accelerator_type == "accelerator_type_value" - assert response.state == cloud_tpu.Node.State.CREATING - assert response.health_description == "health_description_value" - assert response.runtime_version == "runtime_version_value" - assert response.cidr_block == "cidr_block_value" - assert response.health == cloud_tpu.Node.Health.HEALTHY - assert response.tags == ["tags_value"] - assert response.id == 205 - assert response.api_version == cloud_tpu.Node.ApiVersion.V1_ALPHA1 - assert response.queued_resource == "queued_resource_value" - assert response.multislice_node is True + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_node_rest_interceptors(null_interceptor): +def test_start_node_rest_interceptors(null_interceptor): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.TpuRestInterceptor(), @@ -9018,13 +12835,15 @@ def test_get_node_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.TpuRestInterceptor, "post_get_node" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TpuRestInterceptor, "post_start_node" ) as post, mock.patch.object( - transports.TpuRestInterceptor, "pre_get_node" + transports.TpuRestInterceptor, "pre_start_node" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_tpu.GetNodeRequest.pb(cloud_tpu.GetNodeRequest()) + pb_message = cloud_tpu.StartNodeRequest.pb(cloud_tpu.StartNodeRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9035,18 +12854,18 @@ def test_get_node_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = cloud_tpu.Node.to_json(cloud_tpu.Node()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = cloud_tpu.GetNodeRequest() + request = cloud_tpu.StartNodeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = cloud_tpu.Node() + post.return_value = operations_pb2.Operation() - client.get_node( + client.start_node( request, metadata=[ ("key", "val"), @@ -9058,12 +12877,14 @@ def test_get_node_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_node_rest_bad_request(request_type=cloud_tpu.CreateNodeRequest): +def test_update_node_rest_bad_request(request_type=cloud_tpu.UpdateNodeRequest): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "node": {"name": "projects/sample1/locations/sample2/nodes/sample3"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9078,25 +12899,27 @@ def test_create_node_rest_bad_request(request_type=cloud_tpu.CreateNodeRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_node(request) + client.update_node(request) @pytest.mark.parametrize( "request_type", [ - cloud_tpu.CreateNodeRequest, + cloud_tpu.UpdateNodeRequest, dict, ], ) -def test_create_node_rest_call_success(request_type): +def test_update_node_rest_call_success(request_type): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "node": {"name": "projects/sample1/locations/sample2/nodes/sample3"} + } request_init["node"] = { - "name": "name_value", + "name": "projects/sample1/locations/sample2/nodes/sample3", "description": "description_value", "accelerator_type": "accelerator_type_value", "state": 1, @@ -9107,14 +12930,16 @@ def test_create_node_rest_call_success(request_type): "subnetwork": "subnetwork_value", "enable_external_ips": True, "can_ip_forward": True, + "queue_count": 1197, }, + "network_configs": {}, "cidr_block": "cidr_block_value", "service_account": { "email": "email_value", "scope": ["scope_value1", "scope_value2"], }, "create_time": {"seconds": 751, "nanos": 543}, - "scheduling_config": {"preemptible": True, "reserved": True}, + "scheduling_config": {"preemptible": True, "reserved": True, "spot": True}, "network_endpoints": [ { "ip_address": "ip_address_value", @@ -9147,7 +12972,7 @@ def test_create_node_rest_call_success(request_type): # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = cloud_tpu.CreateNodeRequest.meta.fields["node"] + test_field = cloud_tpu.UpdateNodeRequest.meta.fields["node"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -9223,14 +13048,14 @@ def get_message_fields(field): 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_node(request) + response = client.update_node(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_node_rest_interceptors(null_interceptor): +def test_update_node_rest_interceptors(null_interceptor): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.TpuRestInterceptor(), @@ -9244,13 +13069,13 @@ def test_create_node_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.TpuRestInterceptor, "post_create_node" + transports.TpuRestInterceptor, "post_update_node" ) as post, mock.patch.object( - transports.TpuRestInterceptor, "pre_create_node" + transports.TpuRestInterceptor, "pre_update_node" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_tpu.CreateNodeRequest.pb(cloud_tpu.CreateNodeRequest()) + pb_message = cloud_tpu.UpdateNodeRequest.pb(cloud_tpu.UpdateNodeRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9264,7 +13089,7 @@ def test_create_node_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = cloud_tpu.CreateNodeRequest() + request = cloud_tpu.UpdateNodeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9272,7 +13097,7 @@ def test_create_node_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_node( + client.update_node( request, metadata=[ ("key", "val"), @@ -9284,12 +13109,14 @@ def test_create_node_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_node_rest_bad_request(request_type=cloud_tpu.DeleteNodeRequest): +def test_list_queued_resources_rest_bad_request( + request_type=cloud_tpu.ListQueuedResourcesRequest, +): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/nodes/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. @@ -9304,45 +13131,53 @@ def test_delete_node_rest_bad_request(request_type=cloud_tpu.DeleteNodeRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_node(request) + client.list_queued_resources(request) @pytest.mark.parametrize( "request_type", [ - cloud_tpu.DeleteNodeRequest, + cloud_tpu.ListQueuedResourcesRequest, dict, ], ) -def test_delete_node_rest_call_success(request_type): +def test_list_queued_resources_rest_call_success(request_type): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/nodes/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_tpu.ListQueuedResourcesResponse( + 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_tpu.ListQueuedResourcesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_node(request) + response = client.list_queued_resources(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.ListQueuedResourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_node_rest_interceptors(null_interceptor): +def test_list_queued_resources_rest_interceptors(null_interceptor): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.TpuRestInterceptor(), @@ -9354,15 +13189,15 @@ def test_delete_node_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TpuRestInterceptor, "post_delete_node" + transports.TpuRestInterceptor, "post_list_queued_resources" ) as post, mock.patch.object( - transports.TpuRestInterceptor, "pre_delete_node" + transports.TpuRestInterceptor, "pre_list_queued_resources" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_tpu.DeleteNodeRequest.pb(cloud_tpu.DeleteNodeRequest()) + pb_message = cloud_tpu.ListQueuedResourcesRequest.pb( + cloud_tpu.ListQueuedResourcesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9373,18 +13208,20 @@ def test_delete_node_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = cloud_tpu.ListQueuedResourcesResponse.to_json( + cloud_tpu.ListQueuedResourcesResponse() + ) req.return_value.content = return_value - request = cloud_tpu.DeleteNodeRequest() + request = cloud_tpu.ListQueuedResourcesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = cloud_tpu.ListQueuedResourcesResponse() - client.delete_node( + client.list_queued_resources( request, metadata=[ ("key", "val"), @@ -9396,12 +13233,16 @@ def test_delete_node_rest_interceptors(null_interceptor): post.assert_called_once() -def test_stop_node_rest_bad_request(request_type=cloud_tpu.StopNodeRequest): +def test_get_queued_resource_rest_bad_request( + request_type=cloud_tpu.GetQueuedResourceRequest, +): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/nodes/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/queuedResources/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9416,23 +13257,319 @@ def test_stop_node_rest_bad_request(request_type=cloud_tpu.StopNodeRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.stop_node(request) + client.get_queued_resource(request) @pytest.mark.parametrize( "request_type", [ - cloud_tpu.StopNodeRequest, + cloud_tpu.GetQueuedResourceRequest, dict, ], ) -def test_stop_node_rest_call_success(request_type): +def test_get_queued_resource_rest_call_success(request_type): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/nodes/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/queuedResources/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_tpu.QueuedResource( + name="name_value", + reservation_name="reservation_name_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_tpu.QueuedResource.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_queued_resource(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_tpu.QueuedResource) + assert response.name == "name_value" + assert response.reservation_name == "reservation_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_queued_resource_rest_interceptors(null_interceptor): + transport = transports.TpuRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TpuRestInterceptor(), + ) + client = TpuClient(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.TpuRestInterceptor, "post_get_queued_resource" + ) as post, mock.patch.object( + transports.TpuRestInterceptor, "pre_get_queued_resource" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_tpu.GetQueuedResourceRequest.pb( + cloud_tpu.GetQueuedResourceRequest() + ) + 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_tpu.QueuedResource.to_json(cloud_tpu.QueuedResource()) + req.return_value.content = return_value + + request = cloud_tpu.GetQueuedResourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_tpu.QueuedResource() + + client.get_queued_resource( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_queued_resource_rest_bad_request( + request_type=cloud_tpu.CreateQueuedResourceRequest, +): + client = TpuClient( + 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_queued_resource(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_tpu.CreateQueuedResourceRequest, + dict, + ], +) +def test_create_queued_resource_rest_call_success(request_type): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["queued_resource"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "tpu": { + "node_spec": [ + { + "parent": "parent_value", + "node_id": "node_id_value", + "multislice_params": { + "node_count": 1070, + "node_id_prefix": "node_id_prefix_value", + }, + "node": { + "name": "name_value", + "description": "description_value", + "accelerator_type": "accelerator_type_value", + "state": 1, + "health_description": "health_description_value", + "runtime_version": "runtime_version_value", + "network_config": { + "network": "network_value", + "subnetwork": "subnetwork_value", + "enable_external_ips": True, + "can_ip_forward": True, + "queue_count": 1197, + }, + "network_configs": {}, + "cidr_block": "cidr_block_value", + "service_account": { + "email": "email_value", + "scope": ["scope_value1", "scope_value2"], + }, + "create_time": {}, + "scheduling_config": { + "preemptible": True, + "reserved": True, + "spot": True, + }, + "network_endpoints": [ + { + "ip_address": "ip_address_value", + "port": 453, + "access_config": {"external_ip": "external_ip_value"}, + } + ], + "health": 1, + "labels": {}, + "metadata": {}, + "tags": ["tags_value1", "tags_value2"], + "id": 205, + "data_disks": [{"source_disk": "source_disk_value", "mode": 1}], + "api_version": 1, + "symptoms": [ + { + "create_time": {}, + "symptom_type": 1, + "details": "details_value", + "worker_id": "worker_id_value", + } + ], + "shielded_instance_config": {"enable_secure_boot": True}, + "accelerator_config": { + "type_": 2, + "topology": "topology_value", + }, + "queued_resource": "queued_resource_value", + "multislice_node": True, + }, + } + ] + }, + "spot": {}, + "guaranteed": {"min_duration": {"seconds": 751, "nanos": 543}}, + "queueing_policy": { + "valid_until_duration": {}, + "valid_until_time": {}, + "valid_after_duration": {}, + "valid_after_time": {}, + "valid_interval": {"start_time": {}, "end_time": {}}, + }, + "state": { + "state": 1, + "creating_data": {}, + "accepted_data": {}, + "provisioning_data": {}, + "failed_data": { + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + } + }, + "deleting_data": {}, + "active_data": {}, + "suspending_data": {}, + "suspended_data": {}, + "state_initiator": 1, + }, + "reservation_name": "reservation_name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = cloud_tpu.CreateQueuedResourceRequest.meta.fields["queued_resource"] + + 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["queued_resource"].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["queued_resource"][field])): + del request_init["queued_resource"][field][i][subfield] + else: + del request_init["queued_resource"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -9447,14 +13584,14 @@ def test_stop_node_rest_call_success(request_type): 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.stop_node(request) + response = client.create_queued_resource(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_stop_node_rest_interceptors(null_interceptor): +def test_create_queued_resource_rest_interceptors(null_interceptor): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.TpuRestInterceptor(), @@ -9468,13 +13605,15 @@ def test_stop_node_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.TpuRestInterceptor, "post_stop_node" + transports.TpuRestInterceptor, "post_create_queued_resource" ) as post, mock.patch.object( - transports.TpuRestInterceptor, "pre_stop_node" + transports.TpuRestInterceptor, "pre_create_queued_resource" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_tpu.StopNodeRequest.pb(cloud_tpu.StopNodeRequest()) + pb_message = cloud_tpu.CreateQueuedResourceRequest.pb( + cloud_tpu.CreateQueuedResourceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9488,7 +13627,7 @@ def test_stop_node_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = cloud_tpu.StopNodeRequest() + request = cloud_tpu.CreateQueuedResourceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9496,7 +13635,7 @@ def test_stop_node_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.stop_node( + client.create_queued_resource( request, metadata=[ ("key", "val"), @@ -9508,12 +13647,16 @@ def test_stop_node_rest_interceptors(null_interceptor): post.assert_called_once() -def test_start_node_rest_bad_request(request_type=cloud_tpu.StartNodeRequest): +def test_delete_queued_resource_rest_bad_request( + request_type=cloud_tpu.DeleteQueuedResourceRequest, +): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/nodes/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/queuedResources/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9528,23 +13671,25 @@ def test_start_node_rest_bad_request(request_type=cloud_tpu.StartNodeRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.start_node(request) + client.delete_queued_resource(request) @pytest.mark.parametrize( "request_type", [ - cloud_tpu.StartNodeRequest, + cloud_tpu.DeleteQueuedResourceRequest, dict, ], ) -def test_start_node_rest_call_success(request_type): +def test_delete_queued_resource_rest_call_success(request_type): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/nodes/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/queuedResources/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -9559,14 +13704,14 @@ def test_start_node_rest_call_success(request_type): 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.start_node(request) + response = client.delete_queued_resource(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_start_node_rest_interceptors(null_interceptor): +def test_delete_queued_resource_rest_interceptors(null_interceptor): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.TpuRestInterceptor(), @@ -9580,13 +13725,15 @@ def test_start_node_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.TpuRestInterceptor, "post_start_node" + transports.TpuRestInterceptor, "post_delete_queued_resource" ) as post, mock.patch.object( - transports.TpuRestInterceptor, "pre_start_node" + transports.TpuRestInterceptor, "pre_delete_queued_resource" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_tpu.StartNodeRequest.pb(cloud_tpu.StartNodeRequest()) + pb_message = cloud_tpu.DeleteQueuedResourceRequest.pb( + cloud_tpu.DeleteQueuedResourceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9600,7 +13747,7 @@ def test_start_node_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = cloud_tpu.StartNodeRequest() + request = cloud_tpu.DeleteQueuedResourceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9608,7 +13755,7 @@ def test_start_node_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.start_node( + client.delete_queued_resource( request, metadata=[ ("key", "val"), @@ -9620,13 +13767,15 @@ def test_start_node_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_node_rest_bad_request(request_type=cloud_tpu.UpdateNodeRequest): +def test_reset_queued_resource_rest_bad_request( + request_type=cloud_tpu.ResetQueuedResourceRequest, +): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "node": {"name": "projects/sample1/locations/sample2/nodes/sample3"} + "name": "projects/sample1/locations/sample2/queuedResources/sample3" } request = request_type(**request_init) @@ -9642,139 +13791,25 @@ def test_update_node_rest_bad_request(request_type=cloud_tpu.UpdateNodeRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_node(request) + client.reset_queued_resource(request) @pytest.mark.parametrize( "request_type", [ - cloud_tpu.UpdateNodeRequest, + cloud_tpu.ResetQueuedResourceRequest, dict, ], ) -def test_update_node_rest_call_success(request_type): +def test_reset_queued_resource_rest_call_success(request_type): client = TpuClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "node": {"name": "projects/sample1/locations/sample2/nodes/sample3"} - } - request_init["node"] = { - "name": "projects/sample1/locations/sample2/nodes/sample3", - "description": "description_value", - "accelerator_type": "accelerator_type_value", - "state": 1, - "health_description": "health_description_value", - "runtime_version": "runtime_version_value", - "network_config": { - "network": "network_value", - "subnetwork": "subnetwork_value", - "enable_external_ips": True, - "can_ip_forward": True, - }, - "cidr_block": "cidr_block_value", - "service_account": { - "email": "email_value", - "scope": ["scope_value1", "scope_value2"], - }, - "create_time": {"seconds": 751, "nanos": 543}, - "scheduling_config": {"preemptible": True, "reserved": True}, - "network_endpoints": [ - { - "ip_address": "ip_address_value", - "port": 453, - "access_config": {"external_ip": "external_ip_value"}, - } - ], - "health": 1, - "labels": {}, - "metadata": {}, - "tags": ["tags_value1", "tags_value2"], - "id": 205, - "data_disks": [{"source_disk": "source_disk_value", "mode": 1}], - "api_version": 1, - "symptoms": [ - { - "create_time": {}, - "symptom_type": 1, - "details": "details_value", - "worker_id": "worker_id_value", - } - ], - "shielded_instance_config": {"enable_secure_boot": True}, - "accelerator_config": {"type_": 2, "topology": "topology_value"}, - "queued_resource": "queued_resource_value", - "multislice_node": True, + "name": "projects/sample1/locations/sample2/queuedResources/sample3" } - # 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_tpu.UpdateNodeRequest.meta.fields["node"] - - 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["node"].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["node"][field])): - del request_init["node"][field][i][subfield] - else: - del request_init["node"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -9789,14 +13824,14 @@ def get_message_fields(field): 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_node(request) + response = client.reset_queued_resource(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_node_rest_interceptors(null_interceptor): +def test_reset_queued_resource_rest_interceptors(null_interceptor): transport = transports.TpuRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.TpuRestInterceptor(), @@ -9810,13 +13845,15 @@ def test_update_node_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.TpuRestInterceptor, "post_update_node" + transports.TpuRestInterceptor, "post_reset_queued_resource" ) as post, mock.patch.object( - transports.TpuRestInterceptor, "pre_update_node" + transports.TpuRestInterceptor, "pre_reset_queued_resource" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_tpu.UpdateNodeRequest.pb(cloud_tpu.UpdateNodeRequest()) + pb_message = cloud_tpu.ResetQueuedResourceRequest.pb( + cloud_tpu.ResetQueuedResourceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9830,7 +13867,7 @@ def test_update_node_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = cloud_tpu.UpdateNodeRequest() + request = cloud_tpu.ResetQueuedResourceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9838,7 +13875,7 @@ def test_update_node_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.update_node( + client.reset_queued_resource( request, metadata=[ ("key", "val"), @@ -11103,6 +15140,116 @@ def test_update_node_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_queued_resources_empty_call_rest(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_queued_resources), "__call__" + ) as call: + client.list_queued_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.ListQueuedResourcesRequest() + + 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_queued_resource_empty_call_rest(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_queued_resource), "__call__" + ) as call: + client.get_queued_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.GetQueuedResourceRequest() + + 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_queued_resource_empty_call_rest(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_queued_resource), "__call__" + ) as call: + client.create_queued_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.CreateQueuedResourceRequest() + + 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_queued_resource_empty_call_rest(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_queued_resource), "__call__" + ) as call: + client.delete_queued_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.DeleteQueuedResourceRequest() + + 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_reset_queued_resource_empty_call_rest(): + client = TpuClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reset_queued_resource), "__call__" + ) as call: + client.reset_queued_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_tpu.ResetQueuedResourceRequest() + + 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_generate_service_identity_empty_call_rest(): @@ -11292,6 +15439,11 @@ def test_tpu_base_transport(): "stop_node", "start_node", "update_node", + "list_queued_resources", + "get_queued_resource", + "create_queued_resource", + "delete_queued_resource", + "reset_queued_resource", "generate_service_identity", "list_accelerator_types", "get_accelerator_type", @@ -11582,6 +15734,21 @@ def test_tpu_client_transport_session_collision(transport_name): session1 = client1.transport.update_node._session session2 = client2.transport.update_node._session assert session1 != session2 + session1 = client1.transport.list_queued_resources._session + session2 = client2.transport.list_queued_resources._session + assert session1 != session2 + session1 = client1.transport.get_queued_resource._session + session2 = client2.transport.get_queued_resource._session + assert session1 != session2 + session1 = client1.transport.create_queued_resource._session + session2 = client2.transport.create_queued_resource._session + assert session1 != session2 + session1 = client1.transport.delete_queued_resource._session + session2 = client2.transport.delete_queued_resource._session + assert session1 != session2 + session1 = client1.transport.reset_queued_resource._session + session2 = client2.transport.reset_queued_resource._session + assert session1 != session2 session1 = client1.transport.generate_service_identity._session session2 = client2.transport.generate_service_identity._session assert session1 != session2 @@ -11804,10 +15971,36 @@ def test_parse_node_path(): assert expected == actual -def test_runtime_version_path(): +def test_queued_resource_path(): project = "squid" location = "clam" - runtime_version = "whelk" + queued_resource = "whelk" + expected = "projects/{project}/locations/{location}/queuedResources/{queued_resource}".format( + project=project, + location=location, + queued_resource=queued_resource, + ) + actual = TpuClient.queued_resource_path(project, location, queued_resource) + assert expected == actual + + +def test_parse_queued_resource_path(): + expected = { + "project": "octopus", + "location": "oyster", + "queued_resource": "nudibranch", + } + path = TpuClient.queued_resource_path(**expected) + + # Check that the path construction is reversible. + actual = TpuClient.parse_queued_resource_path(path) + assert expected == actual + + +def test_runtime_version_path(): + project = "cuttlefish" + location = "mussel" + runtime_version = "winkle" expected = "projects/{project}/locations/{location}/runtimeVersions/{runtime_version}".format( project=project, location=location, @@ -11819,9 +16012,9 @@ def test_runtime_version_path(): def test_parse_runtime_version_path(): expected = { - "project": "octopus", - "location": "oyster", - "runtime_version": "nudibranch", + "project": "nautilus", + "location": "scallop", + "runtime_version": "abalone", } path = TpuClient.runtime_version_path(**expected) @@ -11831,7 +16024,7 @@ def test_parse_runtime_version_path(): def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -11841,7 +16034,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "clam", } path = TpuClient.common_billing_account_path(**expected) @@ -11851,7 +16044,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -11861,7 +16054,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "octopus", } path = TpuClient.common_folder_path(**expected) @@ -11871,7 +16064,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -11881,7 +16074,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "nudibranch", } path = TpuClient.common_organization_path(**expected) @@ -11891,7 +16084,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -11901,7 +16094,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "mussel", } path = TpuClient.common_project_path(**expected) @@ -11911,8 +16104,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -11923,8 +16116,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "scallop", + "location": "abalone", } path = TpuClient.common_location_path(**expected)