def get_operation(self, name, options=None): """ Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. Example: >>> from google.gapic.longrunning import operations_client >>> api = operations_client.OperationsClient() >>> name = '' >>> response = api.get_operation(name) Args: name (string): The name of the operation resource. options (:class:`google.gax.CallOptions`): Overrides the default settings for this call, e.g, timeout, retries etc. Returns: A :class:`google.longrunning.operations_pb2.Operation` instance. Raises: :exc:`google.gax.errors.GaxError` if the RPC is aborted. :exc:`ValueError` if the parameters are invalid. """ # Create the request object. request = operations_pb2.GetOperationRequest(name=name) return self._get_operation(request, options)
def test_multiple_responses_and_single_response_error(self): channel = grpc_helpers.ChannelStub() stub = operations_pb2.OperationsStub(channel) channel.GetOperation.responses = [] channel.GetOperation.response = mock.sentinel.response with pytest.raises(ValueError): stub.GetOperation(operations_pb2.GetOperationRequest())
def test_no_response(self): channel = grpc_helpers.ChannelStub() stub = operations_pb2.OperationsStub(channel) expected_request = operations_pb2.GetOperationRequest(name="meep") with pytest.raises(ValueError) as exc_info: stub.GetOperation(expected_request) assert exc_info.match("GetOperation")
def test_exception_response(self): channel = grpc_helpers.ChannelStub() stub = operations_pb2.OperationsStub(channel) expected_request = operations_pb2.GetOperationRequest(name="meep") channel.GetOperation.response = RuntimeError() with pytest.raises(RuntimeError): stub.GetOperation(expected_request)
def _get_operation_rpc(self): """Polls the status of the current operation. Uses gRPC request to check. :rtype: :class:`~google.longrunning.operations_pb2.Operation` :returns: The latest status of the current operation. """ request_pb = operations_pb2.GetOperationRequest(name=self.name) return self.client._operations_stub.GetOperation(request_pb)
def test__refresh_grpc(): operations_stub = mock.Mock(spec=["GetOperation"]) expected_result = make_operation_proto(done=True) operations_stub.GetOperation.return_value = expected_result result = operation._refresh_grpc(operations_stub, TEST_OPERATION_NAME) assert result == expected_result expected_request = operations_pb2.GetOperationRequest(name=TEST_OPERATION_NAME) operations_stub.GetOperation.assert_called_once_with(expected_request)
def get_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT, metadata=None, ): """Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. Example: >>> from google.api_core import operations_v1 >>> api = operations_v1.OperationsClient() >>> name = '' >>> response = api.get_operation(name) Args: name (str): The name of the operation resource. retry (google.api_core.retry.Retry): The retry strategy to use when invoking the RPC. If unspecified, the default retry from the client configuration will be used. If ``None``, then this method will not retry the RPC at all. timeout (float): The amount of time in seconds to wait for the RPC to complete. Note that if ``retry`` is used, this timeout applies to each individual attempt and the overall time it takes for this method to complete may be longer. If unspecified, the the default timeout in the client configuration is used. If ``None``, then the RPC method will not time out. metadata (Optional[List[Tuple[str, str]]]): Additional gRPC metadata. Returns: google.longrunning.operations_pb2.Operation: The state of the operation. Raises: google.api_core.exceptions.GoogleAPICallError: If an error occurred while invoking the RPC, the appropriate ``GoogleAPICallError`` subclass will be raised. """ request = operations_pb2.GetOperationRequest(name=name) # Add routing header metadata = metadata or [] metadata.append( gapic_v1.routing_header.to_grpc_metadata({"name": name})) return self._get_operation(request, retry=retry, timeout=timeout, metadata=metadata)
def test_single_response(self): channel = grpc_helpers.ChannelStub() stub = operations_pb2.OperationsStub(channel) expected_request = operations_pb2.GetOperationRequest(name="meep") expected_response = operations_pb2.Operation(name="moop") channel.GetOperation.response = expected_response response = stub.GetOperation(expected_request) assert response == expected_response assert channel.requests == [("GetOperation", expected_request)] assert channel.GetOperation.requests == [expected_request]
def _refresh_grpc(operations_stub, operation_name): """Refresh an operation using a gRPC client. Args: operations_stub (google.longrunning.operations_pb2.OperationsStub): The gRPC operations stub. operation_name (str): The name of the operation. Returns: google.longrunning.operations_pb2.Operation: The operation. """ request_pb = operations_pb2.GetOperationRequest(name=operation_name) return operations_stub.GetOperation(request_pb)
def main(input_uri, encoding, sample_rate, language_code='en-US'): channel = make_channel('speech.googleapis.com', 443) service = cloud_speech_pb2.SpeechStub(channel) # The method and parameters can be inferred from the proto from which the # grpc client lib was generated. See: # https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1beta1/cloud_speech.proto operation = service.AsyncRecognize( cloud_speech_pb2.AsyncRecognizeRequest( config=cloud_speech_pb2.RecognitionConfig( # There are a bunch of config options you can specify. See # https://goo.gl/KPZn97 for the full list. encoding=encoding, # one of LINEAR16, FLAC, MULAW, AMR, AMR_WB sample_rate=sample_rate, # the rate in hertz # See https://g.co/cloud/speech/docs/languages for a list of # supported languages. language_code=language_code, # a BCP-47 language tag ), audio=cloud_speech_pb2.RecognitionAudio(uri=input_uri, )), DEADLINE_SECS) # Print the longrunning operation handle. print(operation) # Construct a long running operation endpoint. service = operations_pb2.OperationsStub(channel) name = operation.name while True: # Give the server a few seconds to process. print('Waiting for server processing...') time.sleep(1) operation = service.GetOperation( operations_pb2.GetOperationRequest(name=name), DEADLINE_SECS) if operation.error.message: print('\nOperation error:\n{}'.format(operation.error)) if operation.done: break response = cloud_speech_pb2.AsyncRecognizeResponse() operation.response.Unpack(response) # Print the recognition result alternatives and confidence scores. for result in response.results: print('Result:') for alternative in result.alternatives: print(u' ({}): {}'.format(alternative.confidence, alternative.transcript))
def test_callable_response(self): channel = grpc_helpers.ChannelStub() stub = operations_pb2.OperationsStub(channel) expected_request = operations_pb2.GetOperationRequest(name="meep") expected_response = operations_pb2.Operation(name="moop") on_get_operation = mock.Mock(spec=("__call__",), return_value=expected_response) channel.GetOperation.response = on_get_operation response = stub.GetOperation(expected_request) assert response == expected_response on_get_operation.assert_called_once_with(expected_request)
def _finished_helper(self, done): from google.longrunning import operations_pb2 from gcloud.bigtable._testing import _FakeStub from gcloud.bigtable.cluster import Cluster PROJECT = 'PROJECT' INSTANCE_ID = 'instance-id' CLUSTER_ID = 'cluster-id' OP_TYPE = 'fake-op' OP_ID = 789 timeout_seconds = 1 client = _Client(PROJECT, timeout_seconds=timeout_seconds) instance = _Instance(INSTANCE_ID, client) cluster = Cluster(CLUSTER_ID, instance) operation = self._makeOne(OP_TYPE, OP_ID, cluster=cluster) # Create request_pb op_name = ('operations/projects/' + PROJECT + '/instances/' + INSTANCE_ID + '/clusters/' + CLUSTER_ID + '/operations/%d' % (OP_ID,)) request_pb = operations_pb2.GetOperationRequest(name=op_name) # Create response_pb response_pb = operations_pb2.Operation(done=done) # Patch the stub used by the API method. client._operations_stub = stub = _FakeStub(response_pb) # Create expected_result. expected_result = done # Perform the method and check the result. result = operation.finished() self.assertEqual(result, expected_result) self.assertEqual(stub.method_calls, [( 'GetOperation', (request_pb, timeout_seconds), {}, )]) if done: self.assertTrue(operation._complete) else: self.assertFalse(operation._complete)
def _finished_helper(self, done): import datetime from google.longrunning import operations_pb2 from gcloud.bigtable._testing import _FakeStub from gcloud.bigtable.cluster import Cluster project = 'PROJECT' zone = 'zone' cluster_id = 'cluster-id' op_type = 'fake-op' op_id = 789 begin = datetime.datetime(2015, 10, 22, 1, 1) timeout_seconds = 1 client = _Client(project, timeout_seconds=timeout_seconds) cluster = Cluster(zone, cluster_id, client) operation = self._makeOne(op_type, op_id, begin, cluster=cluster) # Create request_pb op_name = ('operations/projects/' + project + '/zones/' + zone + '/clusters/' + cluster_id + '/operations/%d' % (op_id,)) request_pb = operations_pb2.GetOperationRequest(name=op_name) # Create response_pb response_pb = operations_pb2.Operation(done=done) # Patch the stub used by the API method. client._operations_stub = stub = _FakeStub(response_pb) # Create expected_result. expected_result = done # Perform the method and check the result. result = operation.finished() self.assertEqual(result, expected_result) self.assertEqual(stub.method_calls, [( 'GetOperation', (request_pb, timeout_seconds), {}, )]) if done: self.assertTrue(operation._complete) else: self.assertFalse(operation._complete)
def test_call_info(self): channel = grpc_helpers.ChannelStub() stub = operations_pb2.OperationsStub(channel) expected_request = operations_pb2.GetOperationRequest(name='meep') expected_response = operations_pb2.Operation(name='moop') expected_metadata = [('red', 'blue'), ('two', 'shoe')] expected_credentials = mock.sentinel.credentials channel.GetOperation.response = expected_response response = stub.GetOperation( expected_request, timeout=42, metadata=expected_metadata, credentials=expected_credentials) assert response == expected_response assert channel.requests == [('GetOperation', expected_request)] assert channel.GetOperation.calls == [ (expected_request, 42, expected_metadata, expected_credentials)]
def _finished_helper(self, done): from google.longrunning import operations_pb2 from gcloud.bigtable._testing import _FakeStub from gcloud.bigtable.instance import Instance PROJECT = 'PROJECT' INSTANCE_ID = 'instance-id' TIMEOUT_SECONDS = 1 client = _Client(PROJECT, timeout_seconds=TIMEOUT_SECONDS) instance = Instance(INSTANCE_ID, client, self.LOCATION_ID) operation = self._makeOne(self.OP_TYPE, self.OP_ID, self.BEGIN, self.LOCATION_ID, instance=instance) # Create request_pb op_name = ('operations/projects/' + PROJECT + '/instances/' + INSTANCE_ID + '/locations/' + self.LOCATION_ID + '/operations/%d' % (self.OP_ID, )) request_pb = operations_pb2.GetOperationRequest(name=op_name) # Create response_pb response_pb = operations_pb2.Operation(done=done) # Patch the stub used by the API method. client._operations_stub = stub = _FakeStub(response_pb) # Create expected_result. expected_result = done # Perform the method and check the result. result = operation.finished() self.assertEqual(result, expected_result) self.assertEqual(stub.method_calls, [( 'GetOperation', (request_pb, TIMEOUT_SECONDS), {}, )]) if done: self.assertTrue(operation._complete) else: self.assertFalse(operation._complete)
def get_operation( self, name: str, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operations_pb2.Operation: r"""Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. Args: name (str): The name of the operation resource. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.longrunning.operations_pb2.Operation: This resource represents a long- unning operation that is the result of a network API call. """ request = operations_pb2.GetOperationRequest(name=name) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata or ()) + ( gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response
def poll(self): """Check if the operation has finished. :rtype: bool :returns: A boolean indicating if the current operation has completed. :raises: :class:`ValueError <exceptions.ValueError>` if the operation has already completed. """ if self.complete: raise ValueError('The operation has completed.') request_pb = operations_pb2.GetOperationRequest(name=self.name) # We expect a `google.longrunning.operations_pb2.Operation`. operation_pb = self.client._operations_stub.GetOperation(request_pb) if operation_pb.done: self._complete = True return self.complete
def _refresh_grpc(operations_stub, operation_name, retry=None): """Refresh an operation using a gRPC client. Args: operations_stub (google.longrunning.operations_pb2.OperationsStub): The gRPC operations stub. operation_name (str): The name of the operation. retry (google.api_core.retry.Retry): (Optional) retry policy Returns: google.longrunning.operations_pb2.Operation: The operation. """ request_pb = operations_pb2.GetOperationRequest(name=operation_name) rpc = operations_stub.GetOperation if retry is not None: rpc = retry(rpc) return rpc(request_pb)
def test_call_info(self): channel = grpc_helpers.ChannelStub() stub = operations_pb2.OperationsStub(channel) expected_request = operations_pb2.GetOperationRequest(name="meep") expected_response = operations_pb2.Operation(name="moop") expected_metadata = [("red", "blue"), ("two", "shoe")] expected_credentials = mock.sentinel.credentials channel.GetOperation.response = expected_response response = stub.GetOperation( expected_request, timeout=42, metadata=expected_metadata, credentials=expected_credentials, ) assert response == expected_response assert channel.requests == [("GetOperation", expected_request)] assert channel.GetOperation.calls == [ (expected_request, 42, expected_metadata, expected_credentials) ]
def finished(self): """Check if the operation has finished. :rtype: bool :returns: A boolean indicating if the current operation has completed. :raises: :class:`ValueError <exceptions.ValueError>` if the operation has already completed. """ if self._complete: raise ValueError('The operation has completed.') operation_name = ('operations/%s/locations/%s/operations/%d' % (self._instance.name, self.location_id, self.op_id)) request_pb = operations_pb2.GetOperationRequest(name=operation_name) # We expect a `google.longrunning.operations_pb2.Operation`. operation_pb = self._instance._client._operations_stub.GetOperation( request_pb, self._instance._client.timeout_seconds) if operation_pb.done: self._complete = True return True else: return False
def test_multiple_responses(self): channel = grpc_helpers.ChannelStub() stub = operations_pb2.OperationsStub(channel) expected_request = operations_pb2.GetOperationRequest(name="meep") expected_responses = [ operations_pb2.Operation(name="foo"), operations_pb2.Operation(name="bar"), operations_pb2.Operation(name="baz"), ] channel.GetOperation.responses = iter(expected_responses) response1 = stub.GetOperation(expected_request) response2 = stub.GetOperation(expected_request) response3 = stub.GetOperation(expected_request) assert response1 == expected_responses[0] assert response2 == expected_responses[1] assert response3 == expected_responses[2] assert channel.requests == [("GetOperation", expected_request)] * 3 assert channel.GetOperation.requests == [expected_request] * 3 with pytest.raises(StopIteration): stub.GetOperation(expected_request)
def _get_operation( self, request: operations_pb2.GetOperationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: request (~.operations_pb2.GetOperationRequest): The request object. The request message for [Operations.GetOperation][google.api_core.operations_v1.Operations.GetOperation]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.operations_pb2.Operation: This resource represents a long- unning operation that is the result of a network API call. """ http_options = [ { "method": "get", "uri": "/v1/{name=operations/**}" }, ] if "google.longrunning.Operations.GetOperation" in self._http_options: http_options = self._http_options[ "google.longrunning.Operations.GetOperation"] request_kwargs = json_format.MessageToDict( request, preserving_proto_field_name=True, including_default_value_fields=True, ) transcoded_request = path_template.transcode(http_options, **request_kwargs) uri = transcoded_request["uri"] method = transcoded_request["method"] # Jsonify the query params query_params_request = operations_pb2.GetOperationRequest() json_format.ParseDict(transcoded_request["query_params"], query_params_request) query_params = json_format.MessageToDict( query_params_request, including_default_value_fields=False, preserving_proto_field_name=False, use_integers_for_enums=False, ) # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "https://{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params), ) # 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 api_response = operations_pb2.Operation() json_format.Parse(response.content, api_response, ignore_unknown_fields=False) return api_response