diff --git a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/gapic_metadata.json b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/gapic_metadata.json index ffc71ff39b10..bd1698a80e72 100644 --- a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/gapic_metadata.json +++ b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/gapic_metadata.json @@ -26,6 +26,16 @@ ] } } + }, + "rest": { + "libraryClient": "PhishingProtectionServiceV1Beta1Client", + "rpcs": { + "ReportPhishing": { + "methods": [ + "report_phishing" + ] + } + } } } } diff --git a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/client.py b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/client.py index f0b0dfc52990..36e43643bb41 100644 --- a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/client.py +++ b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/client.py @@ -56,6 +56,7 @@ from .transports.grpc_asyncio import ( PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport, ) +from .transports.rest import PhishingProtectionServiceV1Beta1RestTransport class PhishingProtectionServiceV1Beta1ClientMeta(type): @@ -73,6 +74,7 @@ class PhishingProtectionServiceV1Beta1ClientMeta(type): _transport_registry[ "grpc_asyncio" ] = PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport + _transport_registry["rest"] = PhishingProtectionServiceV1Beta1RestTransport def get_transport_class( cls, diff --git a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/__init__.py b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/__init__.py index 49895878c350..72b1fb6d9d10 100644 --- a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/__init__.py +++ b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/__init__.py @@ -19,6 +19,10 @@ from .base import PhishingProtectionServiceV1Beta1Transport from .grpc import PhishingProtectionServiceV1Beta1GrpcTransport from .grpc_asyncio import PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport +from .rest import ( + PhishingProtectionServiceV1Beta1RestInterceptor, + PhishingProtectionServiceV1Beta1RestTransport, +) # Compile a registry of transports. _transport_registry = ( @@ -28,9 +32,12 @@ _transport_registry[ "grpc_asyncio" ] = PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport +_transport_registry["rest"] = PhishingProtectionServiceV1Beta1RestTransport __all__ = ( "PhishingProtectionServiceV1Beta1Transport", "PhishingProtectionServiceV1Beta1GrpcTransport", "PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport", + "PhishingProtectionServiceV1Beta1RestTransport", + "PhishingProtectionServiceV1Beta1RestInterceptor", ) diff --git a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/rest.py b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/rest.py new file mode 100644 index 000000000000..49cdaf81d046 --- /dev/null +++ b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/rest.py @@ -0,0 +1,320 @@ +# -*- 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. +# + +import dataclasses +import json # type: ignore +import re +from typing import 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 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.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.phishingprotection_v1beta1.types import phishingprotection + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import PhishingProtectionServiceV1Beta1Transport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class PhishingProtectionServiceV1Beta1RestInterceptor: + """Interceptor for PhishingProtectionServiceV1Beta1. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PhishingProtectionServiceV1Beta1RestTransport. + + .. code-block:: python + class MyCustomPhishingProtectionServiceV1Beta1Interceptor(PhishingProtectionServiceV1Beta1RestInterceptor): + def pre_report_phishing(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_report_phishing(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PhishingProtectionServiceV1Beta1RestTransport(interceptor=MyCustomPhishingProtectionServiceV1Beta1Interceptor()) + client = PhishingProtectionServiceV1Beta1Client(transport=transport) + + + """ + + def pre_report_phishing( + self, + request: phishingprotection.ReportPhishingRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[phishingprotection.ReportPhishingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for report_phishing + + Override in a subclass to manipulate the request or metadata + before they are sent to the PhishingProtectionServiceV1Beta1 server. + """ + return request, metadata + + def post_report_phishing( + self, response: phishingprotection.ReportPhishingResponse + ) -> phishingprotection.ReportPhishingResponse: + """Post-rpc interceptor for report_phishing + + Override in a subclass to manipulate the response + after it is returned by the PhishingProtectionServiceV1Beta1 server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PhishingProtectionServiceV1Beta1RestStub: + _session: AuthorizedSession + _host: str + _interceptor: PhishingProtectionServiceV1Beta1RestInterceptor + + +class PhishingProtectionServiceV1Beta1RestTransport( + PhishingProtectionServiceV1Beta1Transport +): + """REST backend transport for PhishingProtectionServiceV1Beta1. + + Service to report phishing URIs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "phishingprotection.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[PhishingProtectionServiceV1Beta1RestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = ( + interceptor or PhishingProtectionServiceV1Beta1RestInterceptor() + ) + self._prep_wrapped_messages(client_info) + + class _ReportPhishing(PhishingProtectionServiceV1Beta1RestStub): + def __hash__(self): + return hash("ReportPhishing") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @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: phishingprotection.ReportPhishingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> phishingprotection.ReportPhishingResponse: + r"""Call the report phishing method over HTTP. + + Args: + request (~.phishingprotection.ReportPhishingRequest): + The request object. The ReportPhishing request message. + 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: + ~.phishingprotection.ReportPhishingResponse: + The ReportPhishing (empty) response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*}/phishing:report", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_report_phishing(request, metadata) + pb_request = phishingprotection.ReportPhishingRequest.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 = phishingprotection.ReportPhishingResponse() + pb_resp = phishingprotection.ReportPhishingResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_report_phishing(resp) + return resp + + @property + def report_phishing( + self, + ) -> Callable[ + [phishingprotection.ReportPhishingRequest], + phishingprotection.ReportPhishingResponse, + ]: + # 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._ReportPhishing(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PhishingProtectionServiceV1Beta1RestTransport",) diff --git a/packages/google-cloud-phishing-protection/tests/unit/gapic/phishingprotection_v1beta1/test_phishing_protection_service_v1_beta1.py b/packages/google-cloud-phishing-protection/tests/unit/gapic/phishingprotection_v1beta1/test_phishing_protection_service_v1_beta1.py index 11491e3f8c39..60a392a723ea 100644 --- a/packages/google-cloud-phishing-protection/tests/unit/gapic/phishingprotection_v1beta1/test_phishing_protection_service_v1_beta1.py +++ b/packages/google-cloud-phishing-protection/tests/unit/gapic/phishingprotection_v1beta1/test_phishing_protection_service_v1_beta1.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,11 +33,14 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.phishingprotection_v1beta1.services.phishing_protection_service_v1_beta1 import ( PhishingProtectionServiceV1Beta1AsyncClient, @@ -103,6 +108,7 @@ def test__get_default_mtls_endpoint(): [ (PhishingProtectionServiceV1Beta1Client, "grpc"), (PhishingProtectionServiceV1Beta1AsyncClient, "grpc_asyncio"), + (PhishingProtectionServiceV1Beta1Client, "rest"), ], ) def test_phishing_protection_service_v1_beta1_client_from_service_account_info( @@ -118,7 +124,11 @@ def test_phishing_protection_service_v1_beta1_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("phishingprotection.googleapis.com:443") + assert client.transport._host == ( + "phishingprotection.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://phishingprotection.googleapis.com" + ) @pytest.mark.parametrize( @@ -129,6 +139,7 @@ def test_phishing_protection_service_v1_beta1_client_from_service_account_info( transports.PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport, "grpc_asyncio", ), + (transports.PhishingProtectionServiceV1Beta1RestTransport, "rest"), ], ) def test_phishing_protection_service_v1_beta1_client_service_account_always_use_jwt( @@ -154,6 +165,7 @@ def test_phishing_protection_service_v1_beta1_client_service_account_always_use_ [ (PhishingProtectionServiceV1Beta1Client, "grpc"), (PhishingProtectionServiceV1Beta1AsyncClient, "grpc_asyncio"), + (PhishingProtectionServiceV1Beta1Client, "rest"), ], ) def test_phishing_protection_service_v1_beta1_client_from_service_account_file( @@ -176,13 +188,18 @@ def test_phishing_protection_service_v1_beta1_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("phishingprotection.googleapis.com:443") + assert client.transport._host == ( + "phishingprotection.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://phishingprotection.googleapis.com" + ) def test_phishing_protection_service_v1_beta1_client_get_transport_class(): transport = PhishingProtectionServiceV1Beta1Client.get_transport_class() available_transports = [ transports.PhishingProtectionServiceV1Beta1GrpcTransport, + transports.PhishingProtectionServiceV1Beta1RestTransport, ] assert transport in available_transports @@ -203,6 +220,11 @@ def test_phishing_protection_service_v1_beta1_client_get_transport_class(): transports.PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport, "grpc_asyncio", ), + ( + PhishingProtectionServiceV1Beta1Client, + transports.PhishingProtectionServiceV1Beta1RestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -362,6 +384,18 @@ def test_phishing_protection_service_v1_beta1_client_client_options( "grpc_asyncio", "false", ), + ( + PhishingProtectionServiceV1Beta1Client, + transports.PhishingProtectionServiceV1Beta1RestTransport, + "rest", + "true", + ), + ( + PhishingProtectionServiceV1Beta1Client, + transports.PhishingProtectionServiceV1Beta1RestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -571,6 +605,11 @@ def test_phishing_protection_service_v1_beta1_client_get_mtls_endpoint_and_cert_ transports.PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport, "grpc_asyncio", ), + ( + PhishingProtectionServiceV1Beta1Client, + transports.PhishingProtectionServiceV1Beta1RestTransport, + "rest", + ), ], ) def test_phishing_protection_service_v1_beta1_client_client_options_scopes( @@ -611,6 +650,12 @@ def test_phishing_protection_service_v1_beta1_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + PhishingProtectionServiceV1Beta1Client, + transports.PhishingProtectionServiceV1Beta1RestTransport, + "rest", + None, + ), ], ) def test_phishing_protection_service_v1_beta1_client_client_options_credentials_file( @@ -960,6 +1005,287 @@ async def test_report_phishing_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + phishingprotection.ReportPhishingRequest, + dict, + ], +) +def test_report_phishing_rest(request_type): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = phishingprotection.ReportPhishingResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = phishingprotection.ReportPhishingResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.report_phishing(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, phishingprotection.ReportPhishingResponse) + + +def test_report_phishing_rest_required_fields( + request_type=phishingprotection.ReportPhishingRequest, +): + transport_class = transports.PhishingProtectionServiceV1Beta1RestTransport + + request_init = {} + request_init["parent"] = "" + request_init["uri"] = "" + 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, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_phishing._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["uri"] = "uri_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_phishing._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "uri" in jsonified_request + assert jsonified_request["uri"] == "uri_value" + + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = phishingprotection.ReportPhishingResponse() + # 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 + + pb_return_value = phishingprotection.ReportPhishingResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.report_phishing(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_report_phishing_rest_unset_required_fields(): + transport = transports.PhishingProtectionServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.report_phishing._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "uri", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_report_phishing_rest_interceptors(null_interceptor): + transport = transports.PhishingProtectionServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PhishingProtectionServiceV1Beta1RestInterceptor(), + ) + client = PhishingProtectionServiceV1Beta1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PhishingProtectionServiceV1Beta1RestInterceptor, + "post_report_phishing", + ) as post, mock.patch.object( + transports.PhishingProtectionServiceV1Beta1RestInterceptor, + "pre_report_phishing", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = phishingprotection.ReportPhishingRequest.pb( + phishingprotection.ReportPhishingRequest() + ) + 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 = phishingprotection.ReportPhishingResponse.to_json( + phishingprotection.ReportPhishingResponse() + ) + + request = phishingprotection.ReportPhishingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = phishingprotection.ReportPhishingResponse() + + client.report_phishing( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_report_phishing_rest_bad_request( + transport: str = "rest", request_type=phishingprotection.ReportPhishingRequest +): + client = PhishingProtectionServiceV1Beta1Client( + 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.report_phishing(request) + + +def test_report_phishing_rest_flattened(): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = phishingprotection.ReportPhishingResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + uri="uri_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = phishingprotection.ReportPhishingResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.report_phishing(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*}/phishing:report" % client.transport._host, + args[1], + ) + + +def test_report_phishing_rest_flattened_error(transport: str = "rest"): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.report_phishing( + phishingprotection.ReportPhishingRequest(), + parent="parent_value", + uri="uri_value", + ) + + +def test_report_phishing_rest_error(): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PhishingProtectionServiceV1Beta1GrpcTransport( @@ -1041,6 +1367,7 @@ def test_transport_get_channel(): [ transports.PhishingProtectionServiceV1Beta1GrpcTransport, transports.PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport, + transports.PhishingProtectionServiceV1Beta1RestTransport, ], ) def test_transport_adc(transport_class): @@ -1055,6 +1382,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1184,6 +1512,7 @@ def test_phishing_protection_service_v1_beta1_transport_auth_adc(transport_class [ transports.PhishingProtectionServiceV1Beta1GrpcTransport, transports.PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport, + transports.PhishingProtectionServiceV1Beta1RestTransport, ], ) def test_phishing_protection_service_v1_beta1_transport_auth_gdch_credentials( @@ -1290,11 +1619,23 @@ def test_phishing_protection_service_v1_beta1_grpc_transport_client_cert_source_ ) +def test_phishing_protection_service_v1_beta1_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.PhishingProtectionServiceV1Beta1RestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_phishing_protection_service_v1_beta1_host_no_port(transport_name): @@ -1305,7 +1646,11 @@ def test_phishing_protection_service_v1_beta1_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("phishingprotection.googleapis.com:443") + assert client.transport._host == ( + "phishingprotection.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://phishingprotection.googleapis.com" + ) @pytest.mark.parametrize( @@ -1313,6 +1658,7 @@ def test_phishing_protection_service_v1_beta1_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_phishing_protection_service_v1_beta1_host_with_port(transport_name): @@ -1323,7 +1669,35 @@ def test_phishing_protection_service_v1_beta1_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("phishingprotection.googleapis.com:8000") + assert client.transport._host == ( + "phishingprotection.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://phishingprotection.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_phishing_protection_service_v1_beta1_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = PhishingProtectionServiceV1Beta1Client( + credentials=creds1, + transport=transport_name, + ) + client2 = PhishingProtectionServiceV1Beta1Client( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.report_phishing._session + session2 = client2.transport.report_phishing._session + assert session1 != session2 def test_phishing_protection_service_v1_beta1_grpc_transport_channel(): @@ -1606,6 +1980,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -1623,6 +1998,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: