From 509049f04e70580341551df3f323194c4d39f5be Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 19 May 2023 15:41:29 -0400 Subject: [PATCH] feat: add SubmitUri endpoint (#264) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add SubmitUri endpoint PiperOrigin-RevId: 533110799 Source-Link: https://github.com/googleapis/googleapis/commit/3f5d0c91f96df8666fd4c58e5aad6d4e17469f9e Source-Link: https://github.com/googleapis/googleapis-gen/commit/530de5758e4e2cdb6af6d0cab7ad829171142a1f Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTMwZGU1NzU4ZTRlMmNkYjZhZjZkMGNhYjdhZDgyOTE3MTE0MmExZiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot --- .../google/cloud/webrisk/__init__.py | 8 + .../google/cloud/webrisk_v1/__init__.py | 8 + .../cloud/webrisk_v1/gapic_metadata.json | 15 + .../services/web_risk_service/async_client.py | 330 ++++ .../services/web_risk_service/client.py | 331 ++++ .../web_risk_service/transports/base.py | 55 +- .../web_risk_service/transports/grpc.py | 125 +- .../transports/grpc_asyncio.py | 127 +- .../web_risk_service/transports/rest.py | 550 ++++++- .../google/cloud/webrisk_v1/types/__init__.py | 8 + .../google/cloud/webrisk_v1/types/webrisk.py | 302 ++++ ...ppet_metadata_google.cloud.webrisk.v1.json | 155 +- ...metadata_google.cloud.webrisk.v1beta1.json | 2 +- ...rated_web_risk_service_submit_uri_async.py | 60 + ...erated_web_risk_service_submit_uri_sync.py | 60 + .../scripts/fixup_webrisk_v1_keywords.py | 1 + .../gapic/webrisk_v1/test_web_risk_service.py | 1443 +++++++++++++++-- 17 files changed, 3470 insertions(+), 110 deletions(-) create mode 100644 packages/google-cloud-webrisk/samples/generated_samples/webrisk_v1_generated_web_risk_service_submit_uri_async.py create mode 100644 packages/google-cloud-webrisk/samples/generated_samples/webrisk_v1_generated_web_risk_service_submit_uri_sync.py diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk/__init__.py b/packages/google-cloud-webrisk/google/cloud/webrisk/__init__.py index f8b0db3b58ef..8edd5605f471 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk/__init__.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk/__init__.py @@ -37,8 +37,12 @@ SearchUrisRequest, SearchUrisResponse, Submission, + SubmitUriMetadata, + SubmitUriRequest, + ThreatDiscovery, ThreatEntryAdditions, ThreatEntryRemovals, + ThreatInfo, ThreatType, ) @@ -56,8 +60,12 @@ "SearchUrisRequest", "SearchUrisResponse", "Submission", + "SubmitUriMetadata", + "SubmitUriRequest", + "ThreatDiscovery", "ThreatEntryAdditions", "ThreatEntryRemovals", + "ThreatInfo", "CompressionType", "ThreatType", ) diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/__init__.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/__init__.py index d69c703a6a45..0faa1b8779da 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/__init__.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/__init__.py @@ -32,8 +32,12 @@ SearchUrisRequest, SearchUrisResponse, Submission, + SubmitUriMetadata, + SubmitUriRequest, + ThreatDiscovery, ThreatEntryAdditions, ThreatEntryRemovals, + ThreatInfo, ThreatType, ) @@ -51,8 +55,12 @@ "SearchUrisRequest", "SearchUrisResponse", "Submission", + "SubmitUriMetadata", + "SubmitUriRequest", + "ThreatDiscovery", "ThreatEntryAdditions", "ThreatEntryRemovals", + "ThreatInfo", "ThreatType", "WebRiskServiceClient", ) diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/gapic_metadata.json b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/gapic_metadata.json index 8a1f2eba26b1..5e70339a267d 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/gapic_metadata.json +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/gapic_metadata.json @@ -29,6 +29,11 @@ "methods": [ "search_uris" ] + }, + "SubmitUri": { + "methods": [ + "submit_uri" + ] } } }, @@ -54,6 +59,11 @@ "methods": [ "search_uris" ] + }, + "SubmitUri": { + "methods": [ + "submit_uri" + ] } } }, @@ -79,6 +89,11 @@ "methods": [ "search_uris" ] + }, + "SubmitUri": { + "methods": [ + "submit_uri" + ] } } } diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/async_client.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/async_client.py index 0fe829bb2b08..13adc3dc48fc 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/async_client.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/async_client.py @@ -42,6 +42,9 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.webrisk_v1.types import webrisk @@ -727,6 +730,333 @@ async def sample_create_submission(): # Done; return the response. return response + async def submit_uri( + self, + request: Optional[Union[webrisk.SubmitUriRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Submits a URI suspected of containing malicious content to be + reviewed. Returns a google.longrunning.Operation which, once the + review is complete, is updated with its result. You can use the + [Pub/Sub API] (https://cloud.google.com/pubsub) to receive + notifications for the returned Operation. If the result verifies + the existence of malicious content, the site will be added to + the [Google's Social Engineering lists] + (https://support.google.com/webmasters/answer/6350487/) in order + to protect users that could get exposed to this threat in the + future. Only allowlisted projects can use this method during + Early Access. Please reach out to Sales or your customer + engineer to obtain access. + + .. 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 webrisk_v1 + + async def sample_submit_uri(): + # Create a client + client = webrisk_v1.WebRiskServiceAsyncClient() + + # Initialize request argument(s) + submission = webrisk_v1.Submission() + submission.uri = "uri_value" + + request = webrisk_v1.SubmitUriRequest( + parent="parent_value", + submission=submission, + ) + + # Make the request + operation = client.submit_uri(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.webrisk_v1.types.SubmitUriRequest, dict]]): + The request object. Request to send a potentially + malicious URI to WebRisk. + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.webrisk_v1.types.Submission` Wraps + a URI that might be displaying malicious content. + + """ + # Create or coerce a protobuf request object. + request = webrisk.SubmitUriRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.submit_uri, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # 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, + webrisk.Submission, + metadata_type=webrisk.SubmitUriMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + 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.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + 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: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + async def __aenter__(self): return self diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/client.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/client.py index 3ba8ad34fd27..c27554513244 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/client.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/client.py @@ -46,6 +46,9 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.webrisk_v1.types import webrisk @@ -906,6 +909,117 @@ def sample_create_submission(): # Done; return the response. return response + def submit_uri( + self, + request: Optional[Union[webrisk.SubmitUriRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Submits a URI suspected of containing malicious content to be + reviewed. Returns a google.longrunning.Operation which, once the + review is complete, is updated with its result. You can use the + [Pub/Sub API] (https://cloud.google.com/pubsub) to receive + notifications for the returned Operation. If the result verifies + the existence of malicious content, the site will be added to + the [Google's Social Engineering lists] + (https://support.google.com/webmasters/answer/6350487/) in order + to protect users that could get exposed to this threat in the + future. Only allowlisted projects can use this method during + Early Access. Please reach out to Sales or your customer + engineer to obtain access. + + .. 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 webrisk_v1 + + def sample_submit_uri(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + submission = webrisk_v1.Submission() + submission.uri = "uri_value" + + request = webrisk_v1.SubmitUriRequest( + parent="parent_value", + submission=submission, + ) + + # Make the request + operation = client.submit_uri(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.webrisk_v1.types.SubmitUriRequest, dict]): + The request object. Request to send a potentially + malicious URI to WebRisk. + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.webrisk_v1.types.Submission` Wraps + a URI that might be displaying malicious content. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a webrisk.SubmitUriRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, webrisk.SubmitUriRequest): + request = webrisk.SubmitUriRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.submit_uri] + + # 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),)), + ) + + # 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, + webrisk.Submission, + metadata_type=webrisk.SubmitUriMetadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "WebRiskServiceClient": return self @@ -919,6 +1033,223 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + 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.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + 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: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/base.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/base.py index 4c95900810dd..da09f9d32031 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/base.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/base.py @@ -18,10 +18,11 @@ import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.webrisk_v1 import gapic_version as package_version @@ -172,6 +173,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.submit_uri: gapic_v1.method.wrap_method( + self.submit_uri, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -183,6 +189,11 @@ def close(self): """ raise NotImplementedError() + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + @property def compute_threat_list_diff( self, @@ -222,6 +233,48 @@ def create_submission( ]: raise NotImplementedError() + @property + def submit_uri( + self, + ) -> Callable[ + [webrisk.SubmitUriRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc.py index d75c2398e51b..42e70ba1157c 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc.py @@ -16,10 +16,11 @@ from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings -from google.api_core import gapic_v1, grpc_helpers +from google.api_core import gapic_v1, grpc_helpers, operations_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore import grpc # type: ignore from google.cloud.webrisk_v1.types import webrisk @@ -111,6 +112,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -229,6 +231,20 @@ def grpc_channel(self) -> grpc.Channel: """Return the channel designed to connect to this service.""" return self._grpc_channel + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + + # Return the client from cache. + return self._operations_client + @property def compute_threat_list_diff( self, @@ -360,9 +376,116 @@ def create_submission( ) return self._stubs["create_submission"] + @property + def submit_uri( + self, + ) -> Callable[[webrisk.SubmitUriRequest], operations_pb2.Operation]: + r"""Return a callable for the submit uri method over gRPC. + + Submits a URI suspected of containing malicious content to be + reviewed. Returns a google.longrunning.Operation which, once the + review is complete, is updated with its result. You can use the + [Pub/Sub API] (https://cloud.google.com/pubsub) to receive + notifications for the returned Operation. If the result verifies + the existence of malicious content, the site will be added to + the [Google's Social Engineering lists] + (https://support.google.com/webmasters/answer/6350487/) in order + to protect users that could get exposed to this threat in the + future. Only allowlisted projects can use this method during + Early Access. Please reach out to Sales or your customer + engineer to obtain access. + + Returns: + Callable[[~.SubmitUriRequest], + ~.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 "submit_uri" not in self._stubs: + self._stubs["submit_uri"] = self.grpc_channel.unary_unary( + "/google.cloud.webrisk.v1.WebRiskService/SubmitUri", + request_serializer=webrisk.SubmitUriRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["submit_uri"] + def close(self): self.grpc_channel.close() + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + @property def kind(self) -> str: return "grpc" diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc_asyncio.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc_asyncio.py index 10efafab4e07..260bbf27f821 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc_asyncio.py @@ -16,9 +16,10 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -157,6 +158,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -232,6 +234,22 @@ def grpc_channel(self) -> aio.Channel: # Return the channel from cache. return self._grpc_channel + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + @property def compute_threat_list_diff( self, @@ -366,8 +384,115 @@ def create_submission( ) return self._stubs["create_submission"] + @property + def submit_uri( + self, + ) -> Callable[[webrisk.SubmitUriRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the submit uri method over gRPC. + + Submits a URI suspected of containing malicious content to be + reviewed. Returns a google.longrunning.Operation which, once the + review is complete, is updated with its result. You can use the + [Pub/Sub API] (https://cloud.google.com/pubsub) to receive + notifications for the returned Operation. If the result verifies + the existence of malicious content, the site will be added to + the [Google's Social Engineering lists] + (https://support.google.com/webmasters/answer/6350487/) in order + to protect users that could get exposed to this threat in the + future. Only allowlisted projects can use this method during + Early Access. Please reach out to Sales or your customer + engineer to obtain access. + + Returns: + Callable[[~.SubmitUriRequest], + 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 "submit_uri" not in self._stubs: + self._stubs["submit_uri"] = self.grpc_channel.unary_unary( + "/google.cloud.webrisk.v1.WebRiskService/SubmitUri", + request_serializer=webrisk.SubmitUriRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["submit_uri"] + def close(self): return self.grpc_channel.close() + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + __all__ = ("WebRiskServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/rest.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/rest.py index f1e69280cce6..7773d0739fb0 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/rest.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/services/web_risk_service/transports/rest.py @@ -20,12 +20,19 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 from google.protobuf import json_format import grpc # type: ignore from requests import __version__ as requests_version @@ -36,6 +43,8 @@ OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.longrunning import operations_pb2 # type: ignore + from google.cloud.webrisk_v1.types import webrisk from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO @@ -95,6 +104,14 @@ def post_search_uris(self, response): logging.log(f"Received response: {response}") return response + def pre_submit_uri(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_submit_uri(self, response): + logging.log(f"Received response: {response}") + return response + transport = WebRiskServiceRestTransport(interceptor=MyCustomWebRiskServiceInterceptor()) client = WebRiskServiceClient(transport=transport) @@ -189,6 +206,115 @@ def post_search_uris( """ return response + def pre_submit_uri( + self, request: webrisk.SubmitUriRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[webrisk.SubmitUriRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for submit_uri + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebRiskService server. + """ + return request, metadata + + def post_submit_uri( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for submit_uri + + Override in a subclass to manipulate the response + after it is returned by the WebRiskService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebRiskService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the WebRiskService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebRiskService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the WebRiskService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebRiskService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the WebRiskService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebRiskService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the WebRiskService server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class WebRiskServiceRestStub: @@ -282,11 +408,65 @@ def __init__( self._session = AuthorizedSession( self._credentials, default_host=self.DEFAULT_HOST ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) self._interceptor = interceptor or WebRiskServiceRestInterceptor() self._prep_wrapped_messages(client_info) + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1/{name=projects/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + class _ComputeThreatListDiff(WebRiskServiceRestStub): def __hash__(self): return hash("ComputeThreatListDiff") @@ -657,6 +837,103 @@ def __call__( resp = self._interceptor.post_search_uris(resp) return resp + class _SubmitUri(WebRiskServiceRestStub): + def __hash__(self): + return hash("SubmitUri") + + __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 + } + + def __call__( + self, + request: webrisk.SubmitUriRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the submit uri method over HTTP. + + Args: + request (~.webrisk.SubmitUriRequest): + The request object. Request to send a potentially + malicious URI to WebRisk. + 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-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/uris:submit", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_submit_uri(request, metadata) + pb_request = webrisk.SubmitUriRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_submit_uri(resp) + return resp + @property def compute_threat_list_diff( self, @@ -691,6 +968,277 @@ def search_uris( # In C++ this would require a dynamic_cast return self._SearchUris(self._session, self._host, self._interceptor) # type: ignore + @property + def submit_uri( + self, + ) -> Callable[[webrisk.SubmitUriRequest], 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._SubmitUri(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(WebRiskServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(WebRiskServiceRestStub): + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{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 self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(WebRiskServiceRestStub): + def __call__( + 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 for GetOperation method. + 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: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{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) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(WebRiskServiceRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + 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.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{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) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/types/__init__.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/types/__init__.py index 5163a0baf23f..c9aa32297108 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/types/__init__.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/types/__init__.py @@ -26,8 +26,12 @@ SearchUrisRequest, SearchUrisResponse, Submission, + SubmitUriMetadata, + SubmitUriRequest, + ThreatDiscovery, ThreatEntryAdditions, ThreatEntryRemovals, + ThreatInfo, ThreatType, ) @@ -43,8 +47,12 @@ "SearchUrisRequest", "SearchUrisResponse", "Submission", + "SubmitUriMetadata", + "SubmitUriRequest", + "ThreatDiscovery", "ThreatEntryAdditions", "ThreatEntryRemovals", + "ThreatInfo", "CompressionType", "ThreatType", ) diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/types/webrisk.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/types/webrisk.py index 22719c50c2b0..fdc86820e69e 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/types/webrisk.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/types/webrisk.py @@ -37,7 +37,11 @@ "RawHashes", "RiceDeltaEncoding", "Submission", + "ThreatInfo", + "ThreatDiscovery", "CreateSubmissionRequest", + "SubmitUriRequest", + "SubmitUriMetadata", }, ) @@ -555,12 +559,215 @@ class Submission(proto.Message): uri (str): Required. The URI that is being reported for malicious content to be analyzed. + threat_types (MutableSequence[google.cloud.webrisk_v1.types.ThreatType]): + Output only. ThreatTypes found to be + associated with the submitted URI after + reviewing it. This might be empty if the URI was + not added to any list. """ uri: str = proto.Field( proto.STRING, number=1, ) + threat_types: MutableSequence["ThreatType"] = proto.RepeatedField( + proto.ENUM, + number=2, + enum="ThreatType", + ) + + +class ThreatInfo(proto.Message): + r"""Context about the submission including the type of abuse found on + the URI and supporting details. option + (google.api.message_visibility).restriction = "TRUSTED_TESTER"; + + Attributes: + abuse_type (google.cloud.webrisk_v1.types.ThreatInfo.AbuseType): + The type of abuse. + threat_confidence (google.cloud.webrisk_v1.types.ThreatInfo.Confidence): + Confidence that the URI is unsafe. + threat_justification (google.cloud.webrisk_v1.types.ThreatInfo.ThreatJustification): + Context about why the URI is unsafe. + """ + + class AbuseType(proto.Enum): + r"""The abuse type found on the URI. + + Values: + ABUSE_TYPE_UNSPECIFIED (0): + Default. + MALWARE (1): + The URI contains malware. + SOCIAL_ENGINEERING (2): + The URI contains social engineering. + UNWANTED_SOFTWARE (3): + The URI contains unwanted software. + """ + ABUSE_TYPE_UNSPECIFIED = 0 + MALWARE = 1 + SOCIAL_ENGINEERING = 2 + UNWANTED_SOFTWARE = 3 + + class Confidence(proto.Message): + r"""Confidence that a URI is unsafe. + + 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: + score (float): + A decimal representation of confidence in the + range of 0 to 1 where 0 indicates no confidence + and 1 indicates complete confidence. + + This field is a member of `oneof`_ ``value``. + level (google.cloud.webrisk_v1.types.ThreatInfo.Confidence.ConfidenceLevel): + Enum representation of confidence. + + This field is a member of `oneof`_ ``value``. + """ + + class ConfidenceLevel(proto.Enum): + r"""Enum representation of confidence. + + Values: + CONFIDENCE_LEVEL_UNSPECIFIED (0): + Default. + LOW (1): + Less than 60% confidence that the URI is + unsafe. + MEDIUM (2): + Between 60% and 80% confidence that the URI + is unsafe. + HIGH (3): + Greater than 80% confidence that the URI is + unsafe. + """ + CONFIDENCE_LEVEL_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + + score: float = proto.Field( + proto.FLOAT, + number=1, + oneof="value", + ) + level: "ThreatInfo.Confidence.ConfidenceLevel" = proto.Field( + proto.ENUM, + number=2, + oneof="value", + enum="ThreatInfo.Confidence.ConfidenceLevel", + ) + + class ThreatJustification(proto.Message): + r"""Context about why the URI is unsafe. + + Attributes: + labels (MutableSequence[google.cloud.webrisk_v1.types.ThreatInfo.ThreatJustification.JustificationLabel]): + Labels associated with this URI that explain + how it was classified. + comments (MutableSequence[str]): + Free-form context on why this URI is unsafe. + """ + + class JustificationLabel(proto.Enum): + r"""Labels that explain how the URI was classified. + + Values: + JUSTIFICATION_LABEL_UNSPECIFIED (0): + Default. + MANUAL_VERIFICATION (1): + The submitter manually verified that the + submission is unsafe. + USER_REPORT (2): + The submitter received the submission from an + end user. + AUTOMATED_REPORT (3): + The submitter received the submission from an + automated system. + """ + JUSTIFICATION_LABEL_UNSPECIFIED = 0 + MANUAL_VERIFICATION = 1 + USER_REPORT = 2 + AUTOMATED_REPORT = 3 + + labels: MutableSequence[ + "ThreatInfo.ThreatJustification.JustificationLabel" + ] = proto.RepeatedField( + proto.ENUM, + number=1, + enum="ThreatInfo.ThreatJustification.JustificationLabel", + ) + comments: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + abuse_type: AbuseType = proto.Field( + proto.ENUM, + number=1, + enum=AbuseType, + ) + threat_confidence: Confidence = proto.Field( + proto.MESSAGE, + number=2, + message=Confidence, + ) + threat_justification: ThreatJustification = proto.Field( + proto.MESSAGE, + number=3, + message=ThreatJustification, + ) + + +class ThreatDiscovery(proto.Message): + r"""Details about how the threat was discovered. + + Attributes: + platform (google.cloud.webrisk_v1.types.ThreatDiscovery.Platform): + Platform on which the threat was discovered. + region_codes (MutableSequence[str]): + CLDR region code of the countries/regions the + URI poses a threat ordered from most impact to + least impact. Example: "US" for United States. + """ + + class Platform(proto.Enum): + r"""Platform types. + + Values: + PLATFORM_UNSPECIFIED (0): + Default. + ANDROID (1): + General Android platform. + IOS (2): + General iOS platform. + MACOS (3): + General macOS platform. + WINDOWS (4): + General Windows platform. + """ + PLATFORM_UNSPECIFIED = 0 + ANDROID = 1 + IOS = 2 + MACOS = 3 + WINDOWS = 4 + + platform: Platform = proto.Field( + proto.ENUM, + number=1, + enum=Platform, + ) + region_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) class CreateSubmissionRequest(proto.Message): @@ -587,4 +794,99 @@ class CreateSubmissionRequest(proto.Message): ) +class SubmitUriRequest(proto.Message): + r"""Request to send a potentially malicious URI to WebRisk. + + Attributes: + parent (str): + Required. The name of the project that is making the + submission. This string is in the format + "projects/{project_number}". + submission (google.cloud.webrisk_v1.types.Submission): + Required. The submission that contains the + URI to be scanned. + threat_info (google.cloud.webrisk_v1.types.ThreatInfo): + Provides additional information about the + submission. + threat_discovery (google.cloud.webrisk_v1.types.ThreatDiscovery): + Provides additional information about how the + submission was discovered. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + submission: "Submission" = proto.Field( + proto.MESSAGE, + number=2, + message="Submission", + ) + threat_info: "ThreatInfo" = proto.Field( + proto.MESSAGE, + number=3, + message="ThreatInfo", + ) + threat_discovery: "ThreatDiscovery" = proto.Field( + proto.MESSAGE, + number=4, + message="ThreatDiscovery", + ) + + +class SubmitUriMetadata(proto.Message): + r"""Metadata for the Submit URI long-running operation. option + (google.api.message_visibility).restriction = "TRUSTED_TESTER"; + + Attributes: + state (google.cloud.webrisk_v1.types.SubmitUriMetadata.State): + The state of the operation. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Creation time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Latest update time of the operation. + """ + + class State(proto.Enum): + r"""Enum that represents the state of the long-running operation. + + Values: + STATE_UNSPECIFIED (0): + Default unspecified state. + RUNNING (1): + The operation is currently running. + SUCCEEDED (2): + The operation finished with a success status. + CANCELLED (3): + The operation was cancelled. + FAILED (4): + The operation finished with a failure status. + CLOSED (5): + The operation was closed with no action + taken. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + CANCELLED = 3 + FAILED = 4 + CLOSED = 5 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1.json b/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1.json index 546738313e12..1a29be137849 100644 --- a/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1.json +++ b/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-webrisk", - "version": "1.11.1" + "version": "0.1.0" }, "snippets": [ { @@ -694,6 +694,159 @@ } ], "title": "webrisk_v1_generated_web_risk_service_search_uris_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.webrisk_v1.WebRiskServiceAsyncClient", + "shortName": "WebRiskServiceAsyncClient" + }, + "fullName": "google.cloud.webrisk_v1.WebRiskServiceAsyncClient.submit_uri", + "method": { + "fullName": "google.cloud.webrisk.v1.WebRiskService.SubmitUri", + "service": { + "fullName": "google.cloud.webrisk.v1.WebRiskService", + "shortName": "WebRiskService" + }, + "shortName": "SubmitUri" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.webrisk_v1.types.SubmitUriRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "submit_uri" + }, + "description": "Sample for SubmitUri", + "file": "webrisk_v1_generated_web_risk_service_submit_uri_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "webrisk_v1_generated_WebRiskService_SubmitUri_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "webrisk_v1_generated_web_risk_service_submit_uri_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.webrisk_v1.WebRiskServiceClient", + "shortName": "WebRiskServiceClient" + }, + "fullName": "google.cloud.webrisk_v1.WebRiskServiceClient.submit_uri", + "method": { + "fullName": "google.cloud.webrisk.v1.WebRiskService.SubmitUri", + "service": { + "fullName": "google.cloud.webrisk.v1.WebRiskService", + "shortName": "WebRiskService" + }, + "shortName": "SubmitUri" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.webrisk_v1.types.SubmitUriRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "submit_uri" + }, + "description": "Sample for SubmitUri", + "file": "webrisk_v1_generated_web_risk_service_submit_uri_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "webrisk_v1_generated_WebRiskService_SubmitUri_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "webrisk_v1_generated_web_risk_service_submit_uri_sync.py" } ] } diff --git a/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1beta1.json b/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1beta1.json index 755a1bc24c66..de1e97aff4a5 100644 --- a/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1beta1.json +++ b/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-webrisk", - "version": "1.11.1" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-webrisk/samples/generated_samples/webrisk_v1_generated_web_risk_service_submit_uri_async.py b/packages/google-cloud-webrisk/samples/generated_samples/webrisk_v1_generated_web_risk_service_submit_uri_async.py new file mode 100644 index 000000000000..63454bad165e --- /dev/null +++ b/packages/google-cloud-webrisk/samples/generated_samples/webrisk_v1_generated_web_risk_service_submit_uri_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 SubmitUri +# 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-webrisk + + +# [START webrisk_v1_generated_WebRiskService_SubmitUri_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 webrisk_v1 + + +async def sample_submit_uri(): + # Create a client + client = webrisk_v1.WebRiskServiceAsyncClient() + + # Initialize request argument(s) + submission = webrisk_v1.Submission() + submission.uri = "uri_value" + + request = webrisk_v1.SubmitUriRequest( + parent="parent_value", + submission=submission, + ) + + # Make the request + operation = client.submit_uri(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END webrisk_v1_generated_WebRiskService_SubmitUri_async] diff --git a/packages/google-cloud-webrisk/samples/generated_samples/webrisk_v1_generated_web_risk_service_submit_uri_sync.py b/packages/google-cloud-webrisk/samples/generated_samples/webrisk_v1_generated_web_risk_service_submit_uri_sync.py new file mode 100644 index 000000000000..fd3a3c90b96b --- /dev/null +++ b/packages/google-cloud-webrisk/samples/generated_samples/webrisk_v1_generated_web_risk_service_submit_uri_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 SubmitUri +# 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-webrisk + + +# [START webrisk_v1_generated_WebRiskService_SubmitUri_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 webrisk_v1 + + +def sample_submit_uri(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + submission = webrisk_v1.Submission() + submission.uri = "uri_value" + + request = webrisk_v1.SubmitUriRequest( + parent="parent_value", + submission=submission, + ) + + # Make the request + operation = client.submit_uri(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END webrisk_v1_generated_WebRiskService_SubmitUri_sync] diff --git a/packages/google-cloud-webrisk/scripts/fixup_webrisk_v1_keywords.py b/packages/google-cloud-webrisk/scripts/fixup_webrisk_v1_keywords.py index 564b3ee8628f..1d869d9813d3 100644 --- a/packages/google-cloud-webrisk/scripts/fixup_webrisk_v1_keywords.py +++ b/packages/google-cloud-webrisk/scripts/fixup_webrisk_v1_keywords.py @@ -43,6 +43,7 @@ class webriskCallTransformer(cst.CSTTransformer): 'create_submission': ('parent', 'submission', ), 'search_hashes': ('threat_types', 'hash_prefix', ), 'search_uris': ('uri', 'threat_types', ), + 'submit_uri': ('parent', 'submission', 'threat_info', 'threat_discovery', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/packages/google-cloud-webrisk/tests/unit/gapic/webrisk_v1/test_web_risk_service.py b/packages/google-cloud-webrisk/tests/unit/gapic/webrisk_v1/test_web_risk_service.py index 28a9a01702e9..2c8ca7ac55df 100644 --- a/packages/google-cloud-webrisk/tests/unit/gapic/webrisk_v1/test_web_risk_service.py +++ b/packages/google-cloud-webrisk/tests/unit/gapic/webrisk_v1/test_web_risk_service.py @@ -26,12 +26,22 @@ import json import math -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 from google.oauth2 import service_account from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore @@ -1303,6 +1313,7 @@ def test_create_submission(request_type, transport: str = "grpc"): # Designate an appropriate return value for the call. call.return_value = webrisk.Submission( uri="uri_value", + threat_types=[webrisk.ThreatType.MALWARE], ) response = client.create_submission(request) @@ -1314,6 +1325,7 @@ def test_create_submission(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, webrisk.Submission) assert response.uri == "uri_value" + assert response.threat_types == [webrisk.ThreatType.MALWARE] def test_create_submission_empty_call(): @@ -1355,6 +1367,7 @@ async def test_create_submission_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( webrisk.Submission( uri="uri_value", + threat_types=[webrisk.ThreatType.MALWARE], ) ) response = await client.create_submission(request) @@ -1367,6 +1380,7 @@ async def test_create_submission_async( # Establish that the response is the type that we expect. assert isinstance(response, webrisk.Submission) assert response.uri == "uri_value" + assert response.threat_types == [webrisk.ThreatType.MALWARE] @pytest.mark.asyncio @@ -1531,6 +1545,150 @@ async def test_create_submission_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + webrisk.SubmitUriRequest, + dict, + ], +) +def test_submit_uri(request_type, transport: str = "grpc"): + client = WebRiskServiceClient( + 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.submit_uri), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.submit_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == webrisk.SubmitUriRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_submit_uri_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.submit_uri), "__call__") as call: + client.submit_uri() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == webrisk.SubmitUriRequest() + + +@pytest.mark.asyncio +async def test_submit_uri_async( + transport: str = "grpc_asyncio", request_type=webrisk.SubmitUriRequest +): + client = WebRiskServiceAsyncClient( + 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.submit_uri), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.submit_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == webrisk.SubmitUriRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_submit_uri_async_from_dict(): + await test_submit_uri_async(request_type=dict) + + +def test_submit_uri_field_headers(): + client = WebRiskServiceClient( + 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 = webrisk.SubmitUriRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.submit_uri), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.submit_uri(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_submit_uri_field_headers_async(): + client = WebRiskServiceAsyncClient( + 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 = webrisk.SubmitUriRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.submit_uri), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.submit_uri(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"] + + @pytest.mark.parametrize( "request_type", [ @@ -2403,7 +2561,7 @@ def test_create_submission_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1"} - request_init["submission"] = {"uri": "uri_value"} + request_init["submission"] = {"uri": "uri_value", "threat_types": [1]} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -2411,6 +2569,7 @@ def test_create_submission_rest(request_type): # Designate an appropriate value for the returned response. return_value = webrisk.Submission( uri="uri_value", + threat_types=[webrisk.ThreatType.MALWARE], ) # Wrap the value into a proper Response obj @@ -2426,6 +2585,7 @@ def test_create_submission_rest(request_type): # Establish that the response is the type that we expect. assert isinstance(response, webrisk.Submission) assert response.uri == "uri_value" + assert response.threat_types == [webrisk.ThreatType.MALWARE] def test_create_submission_rest_required_fields( @@ -2588,7 +2748,7 @@ def test_create_submission_rest_bad_request( # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1"} - request_init["submission"] = {"uri": "uri_value"} + request_init["submission"] = {"uri": "uri_value", "threat_types": [1]} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -2665,121 +2825,334 @@ def test_create_submission_rest_error(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebRiskServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + webrisk.SubmitUriRequest, + dict, + ], +) +def test_submit_uri_rest(request_type): + client = WebRiskServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = WebRiskServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebRiskServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebRiskServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) - # It is an error to provide an api_key and a transport instance. - transport = transports.WebRiskServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WebRiskServiceClient( - client_options=options, - transport=transport, - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WebRiskServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - # It is an error to provide scopes and a transport instance. - transport = transports.WebRiskServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebRiskServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.submit_uri(request) + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebRiskServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WebRiskServiceClient(transport=transport) - assert client.transport is transport +def test_submit_uri_rest_required_fields(request_type=webrisk.SubmitUriRequest): + transport_class = transports.WebRiskServiceRestTransport -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebRiskServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - channel = transport.grpc_channel - assert channel - transport = transports.WebRiskServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # verify fields with default values are dropped + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).submit_uri._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebRiskServiceGrpcTransport, - transports.WebRiskServiceGrpcAsyncIOTransport, - transports.WebRiskServiceRestTransport, - ], -) -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() + # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = WebRiskServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).submit_uri._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" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = WebRiskServiceClient( 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 + + response = client.submit_uri(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_submit_uri_rest_unset_required_fields(): + transport = transports.WebRiskServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.submit_uri._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "submission", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_submit_uri_rest_interceptors(null_interceptor): + transport = transports.WebRiskServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebRiskServiceRestInterceptor(), + ) + client = WebRiskServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.WebRiskServiceRestInterceptor, "post_submit_uri" + ) as post, mock.patch.object( + transports.WebRiskServiceRestInterceptor, "pre_submit_uri" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = webrisk.SubmitUriRequest.pb(webrisk.SubmitUriRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = webrisk.SubmitUriRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.submit_uri( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_submit_uri_rest_bad_request( + transport: str = "rest", request_type=webrisk.SubmitUriRequest +): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.submit_uri(request) + + +def test_submit_uri_rest_error(): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebRiskServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebRiskServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebRiskServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WebRiskServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WebRiskServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WebRiskServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebRiskServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebRiskServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebRiskServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebRiskServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebRiskServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebRiskServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebRiskServiceGrpcTransport, + transports.WebRiskServiceGrpcAsyncIOTransport, + transports.WebRiskServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = WebRiskServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebRiskServiceGrpcTransport, ) - assert isinstance( - client.transport, - transports.WebRiskServiceGrpcTransport, - ) def test_web_risk_service_base_transport_error(): @@ -2808,6 +3181,11 @@ def test_web_risk_service_base_transport(): "search_uris", "search_hashes", "create_submission", + "submit_uri", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2816,6 +3194,11 @@ def test_web_risk_service_base_transport(): with pytest.raises(NotImplementedError): transport.close() + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + # Catch all for all remaining methods and properties remainder = [ "kind", @@ -3003,6 +3386,23 @@ def test_web_risk_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) +def test_web_risk_service_rest_lro_client(): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ @@ -3078,6 +3478,9 @@ def test_web_risk_service_client_transport_session_collision(transport_name): session1 = client1.transport.create_submission._session session2 = client2.transport.create_submission._session assert session1 != session2 + session1 = client1.transport.submit_uri._session + session2 = client2.transport.submit_uri._session + assert session1 != session2 def test_web_risk_service_grpc_transport_channel(): @@ -3206,14 +3609,48 @@ def test_web_risk_service_transport_channel_mtls_with_adc(transport_class): assert transport.grpc_channel == mock_grpc_channel -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +def test_web_risk_service_grpc_lro_client(): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - actual = WebRiskServiceClient.common_billing_account_path(billing_account) - assert expected == actual - + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_web_risk_service_grpc_lro_async_client(): + client = WebRiskServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = WebRiskServiceClient.common_billing_account_path(billing_account) + assert expected == actual + def test_parse_common_billing_account_path(): expected = { @@ -3346,6 +3783,804 @@ async def test_transport_close_async(): close.assert_called_once() +def test_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/operations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/operations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/operations/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() + + # 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 + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = WebRiskServiceClient( + 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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(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 response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc"): + client = WebRiskServiceAsyncClient( + 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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(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 response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = WebRiskServiceClient( + 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 = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = WebRiskServiceAsyncClient( + 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 = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(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=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = WebRiskServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = WebRiskServiceClient( + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(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 response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = WebRiskServiceAsyncClient( + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(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 response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = WebRiskServiceClient( + 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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = WebRiskServiceAsyncClient( + 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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(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=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = WebRiskServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = WebRiskServiceClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = WebRiskServiceAsyncClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = WebRiskServiceClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = WebRiskServiceAsyncClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(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=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = WebRiskServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = WebRiskServiceClient( + 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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = WebRiskServiceAsyncClient( + 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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = WebRiskServiceClient( + 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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = WebRiskServiceAsyncClient( + 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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = WebRiskServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = WebRiskServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + def test_transport_close(): transports = { "rest": "_session",