From b2b9eab649f413d7ad8a47fd660f9e2bcc32a820 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 28 Feb 2023 06:45:51 -0500 Subject: [PATCH] feat: enable "rest" transport in Python for services supporting numeric enums (#418) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: enable "rest" transport in Python for services supporting numeric enums PiperOrigin-RevId: 508143576 Source-Link: https://github.com/googleapis/googleapis/commit/7a702a989db3b413f39ff8994ca53fb38b6928c2 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6ad1279c0e7aa787ac6b66c9fd4a210692edffcd Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNmFkMTI3OWMwZTdhYTc4N2FjNmI2NmM5ZmQ0YTIxMDY5MmVkZmZjZCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * chore: Update gapic-generator-python to v1.8.5 PiperOrigin-RevId: 511892190 Source-Link: https://github.com/googleapis/googleapis/commit/a45d9c09c1287ffdf938f4e8083e791046c0b23b Source-Link: https://github.com/googleapis/googleapis-gen/commit/1907294b1d8365ea24f8c5f2e059a64124c4ed3b Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMTkwNzI5NGIxZDgzNjVlYTI0ZjhjNWYyZTA1OWE2NDEyNGM0ZWQzYiJ9 * 🦉 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 Co-authored-by: Anthonios Partheniou --- .../gapic_metadata.json | 45 + .../services/error_group_service/client.py | 2 + .../transports/__init__.py | 5 + .../error_group_service/transports/rest.py | 447 +++++++ .../services/error_stats_service/client.py | 2 + .../transports/__init__.py | 5 + .../error_stats_service/transports/rest.py | 579 +++++++++ .../services/report_errors_service/client.py | 2 + .../transports/__init__.py | 5 + .../report_errors_service/transports/rest.py | 329 +++++ .../errorreporting_v1beta1/types/common.py | 2 + .../types/error_group_service.py | 2 + .../types/error_stats_service.py | 2 + .../types/report_errors_service.py | 2 + ....devtools.clouderrorreporting.v1beta1.json | 2 +- .../test_error_group_service.py | 644 +++++++++- .../test_error_stats_service.py | 1091 ++++++++++++++++- .../test_report_errors_service.py | 441 ++++++- 18 files changed, 3594 insertions(+), 13 deletions(-) create mode 100644 google/cloud/errorreporting_v1beta1/services/error_group_service/transports/rest.py create mode 100644 google/cloud/errorreporting_v1beta1/services/error_stats_service/transports/rest.py create mode 100644 google/cloud/errorreporting_v1beta1/services/report_errors_service/transports/rest.py diff --git a/google/cloud/errorreporting_v1beta1/gapic_metadata.json b/google/cloud/errorreporting_v1beta1/gapic_metadata.json index 1b6fc5e2..825275e6 100644 --- a/google/cloud/errorreporting_v1beta1/gapic_metadata.json +++ b/google/cloud/errorreporting_v1beta1/gapic_metadata.json @@ -36,6 +36,21 @@ ] } } + }, + "rest": { + "libraryClient": "ErrorGroupServiceClient", + "rpcs": { + "GetGroup": { + "methods": [ + "get_group" + ] + }, + "UpdateGroup": { + "methods": [ + "update_group" + ] + } + } } } }, @@ -80,6 +95,26 @@ ] } } + }, + "rest": { + "libraryClient": "ErrorStatsServiceClient", + "rpcs": { + "DeleteEvents": { + "methods": [ + "delete_events" + ] + }, + "ListEvents": { + "methods": [ + "list_events" + ] + }, + "ListGroupStats": { + "methods": [ + "list_group_stats" + ] + } + } } } }, @@ -104,6 +139,16 @@ ] } } + }, + "rest": { + "libraryClient": "ReportErrorsServiceClient", + "rpcs": { + "ReportErrorEvent": { + "methods": [ + "report_error_event" + ] + } + } } } } diff --git a/google/cloud/errorreporting_v1beta1/services/error_group_service/client.py b/google/cloud/errorreporting_v1beta1/services/error_group_service/client.py index f52ea951..07f0aead 100644 --- a/google/cloud/errorreporting_v1beta1/services/error_group_service/client.py +++ b/google/cloud/errorreporting_v1beta1/services/error_group_service/client.py @@ -51,6 +51,7 @@ from .transports.base import ErrorGroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ErrorGroupServiceGrpcTransport from .transports.grpc_asyncio import ErrorGroupServiceGrpcAsyncIOTransport +from .transports.rest import ErrorGroupServiceRestTransport class ErrorGroupServiceClientMeta(type): @@ -66,6 +67,7 @@ class ErrorGroupServiceClientMeta(type): ) # type: Dict[str, Type[ErrorGroupServiceTransport]] _transport_registry["grpc"] = ErrorGroupServiceGrpcTransport _transport_registry["grpc_asyncio"] = ErrorGroupServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ErrorGroupServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/errorreporting_v1beta1/services/error_group_service/transports/__init__.py b/google/cloud/errorreporting_v1beta1/services/error_group_service/transports/__init__.py index 873035d9..b6d0629c 100644 --- a/google/cloud/errorreporting_v1beta1/services/error_group_service/transports/__init__.py +++ b/google/cloud/errorreporting_v1beta1/services/error_group_service/transports/__init__.py @@ -19,15 +19,20 @@ from .base import ErrorGroupServiceTransport from .grpc import ErrorGroupServiceGrpcTransport from .grpc_asyncio import ErrorGroupServiceGrpcAsyncIOTransport +from .rest import ErrorGroupServiceRestTransport +from .rest import ErrorGroupServiceRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ErrorGroupServiceTransport]] _transport_registry["grpc"] = ErrorGroupServiceGrpcTransport _transport_registry["grpc_asyncio"] = ErrorGroupServiceGrpcAsyncIOTransport +_transport_registry["rest"] = ErrorGroupServiceRestTransport __all__ = ( "ErrorGroupServiceTransport", "ErrorGroupServiceGrpcTransport", "ErrorGroupServiceGrpcAsyncIOTransport", + "ErrorGroupServiceRestTransport", + "ErrorGroupServiceRestInterceptor", ) diff --git a/google/cloud/errorreporting_v1beta1/services/error_group_service/transports/rest.py b/google/cloud/errorreporting_v1beta1/services/error_group_service/transports/rest.py new file mode 100644 index 00000000..a85ea6ea --- /dev/null +++ b/google/cloud/errorreporting_v1beta1/services/error_group_service/transports/rest.py @@ -0,0 +1,447 @@ +# -*- 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.errorreporting_v1beta1.types import common +from google.cloud.errorreporting_v1beta1.types import error_group_service + +from .base import ( + ErrorGroupServiceTransport, + DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO, +) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ErrorGroupServiceRestInterceptor: + """Interceptor for ErrorGroupService. + + 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 ErrorGroupServiceRestTransport. + + .. code-block:: python + class MyCustomErrorGroupServiceInterceptor(ErrorGroupServiceRestInterceptor): + def pre_get_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_group(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ErrorGroupServiceRestTransport(interceptor=MyCustomErrorGroupServiceInterceptor()) + client = ErrorGroupServiceClient(transport=transport) + + + """ + + def pre_get_group( + self, + request: error_group_service.GetGroupRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[error_group_service.GetGroupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the ErrorGroupService server. + """ + return request, metadata + + def post_get_group(self, response: common.ErrorGroup) -> common.ErrorGroup: + """Post-rpc interceptor for get_group + + Override in a subclass to manipulate the response + after it is returned by the ErrorGroupService server but before + it is returned to user code. + """ + return response + + def pre_update_group( + self, + request: error_group_service.UpdateGroupRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[error_group_service.UpdateGroupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the ErrorGroupService server. + """ + return request, metadata + + def post_update_group(self, response: common.ErrorGroup) -> common.ErrorGroup: + """Post-rpc interceptor for update_group + + Override in a subclass to manipulate the response + after it is returned by the ErrorGroupService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ErrorGroupServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ErrorGroupServiceRestInterceptor + + +class ErrorGroupServiceRestTransport(ErrorGroupServiceTransport): + """REST backend transport for ErrorGroupService. + + Service for retrieving and updating individual error groups. + + 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 = "clouderrorreporting.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[ErrorGroupServiceRestInterceptor] = 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 ErrorGroupServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetGroup(ErrorGroupServiceRestStub): + def __hash__(self): + return hash("GetGroup") + + __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: error_group_service.GetGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.ErrorGroup: + r"""Call the get group method over HTTP. + + Args: + request (~.error_group_service.GetGroupRequest): + The request object. A request to return an individual + group. + + 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: + ~.common.ErrorGroup: + Description of a group of similar + error events. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{group_name=projects/*/groups/*}", + }, + ] + request, metadata = self._interceptor.pre_get_group(request, metadata) + pb_request = error_group_service.GetGroupRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + 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), + ) + + # 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 = common.ErrorGroup() + pb_resp = common.ErrorGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_group(resp) + return resp + + class _UpdateGroup(ErrorGroupServiceRestStub): + def __hash__(self): + return hash("UpdateGroup") + + __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: error_group_service.UpdateGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.ErrorGroup: + r"""Call the update group method over HTTP. + + Args: + request (~.error_group_service.UpdateGroupRequest): + The request object. A request to replace the existing + data for the given group. + + 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: + ~.common.ErrorGroup: + Description of a group of similar + error events. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v1beta1/{group.name=projects/*/groups/*}", + "body": "group", + }, + ] + request, metadata = self._interceptor.pre_update_group(request, metadata) + pb_request = error_group_service.UpdateGroupRequest.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 = common.ErrorGroup() + pb_resp = common.ErrorGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_group(resp) + return resp + + @property + def get_group( + self, + ) -> Callable[[error_group_service.GetGroupRequest], common.ErrorGroup]: + # 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._GetGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_group( + self, + ) -> Callable[[error_group_service.UpdateGroupRequest], common.ErrorGroup]: + # 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._UpdateGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ErrorGroupServiceRestTransport",) diff --git a/google/cloud/errorreporting_v1beta1/services/error_stats_service/client.py b/google/cloud/errorreporting_v1beta1/services/error_stats_service/client.py index 1033a8c9..ff3799e4 100644 --- a/google/cloud/errorreporting_v1beta1/services/error_stats_service/client.py +++ b/google/cloud/errorreporting_v1beta1/services/error_stats_service/client.py @@ -52,6 +52,7 @@ from .transports.base import ErrorStatsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ErrorStatsServiceGrpcTransport from .transports.grpc_asyncio import ErrorStatsServiceGrpcAsyncIOTransport +from .transports.rest import ErrorStatsServiceRestTransport class ErrorStatsServiceClientMeta(type): @@ -67,6 +68,7 @@ class ErrorStatsServiceClientMeta(type): ) # type: Dict[str, Type[ErrorStatsServiceTransport]] _transport_registry["grpc"] = ErrorStatsServiceGrpcTransport _transport_registry["grpc_asyncio"] = ErrorStatsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ErrorStatsServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/errorreporting_v1beta1/services/error_stats_service/transports/__init__.py b/google/cloud/errorreporting_v1beta1/services/error_stats_service/transports/__init__.py index 484e788e..b1b560f3 100644 --- a/google/cloud/errorreporting_v1beta1/services/error_stats_service/transports/__init__.py +++ b/google/cloud/errorreporting_v1beta1/services/error_stats_service/transports/__init__.py @@ -19,15 +19,20 @@ from .base import ErrorStatsServiceTransport from .grpc import ErrorStatsServiceGrpcTransport from .grpc_asyncio import ErrorStatsServiceGrpcAsyncIOTransport +from .rest import ErrorStatsServiceRestTransport +from .rest import ErrorStatsServiceRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ErrorStatsServiceTransport]] _transport_registry["grpc"] = ErrorStatsServiceGrpcTransport _transport_registry["grpc_asyncio"] = ErrorStatsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = ErrorStatsServiceRestTransport __all__ = ( "ErrorStatsServiceTransport", "ErrorStatsServiceGrpcTransport", "ErrorStatsServiceGrpcAsyncIOTransport", + "ErrorStatsServiceRestTransport", + "ErrorStatsServiceRestInterceptor", ) diff --git a/google/cloud/errorreporting_v1beta1/services/error_stats_service/transports/rest.py b/google/cloud/errorreporting_v1beta1/services/error_stats_service/transports/rest.py new file mode 100644 index 00000000..779f59c5 --- /dev/null +++ b/google/cloud/errorreporting_v1beta1/services/error_stats_service/transports/rest.py @@ -0,0 +1,579 @@ +# -*- 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.errorreporting_v1beta1.types import error_stats_service + +from .base import ( + ErrorStatsServiceTransport, + DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO, +) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ErrorStatsServiceRestInterceptor: + """Interceptor for ErrorStatsService. + + 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 ErrorStatsServiceRestTransport. + + .. code-block:: python + class MyCustomErrorStatsServiceInterceptor(ErrorStatsServiceRestInterceptor): + def pre_delete_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_group_stats(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_group_stats(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ErrorStatsServiceRestTransport(interceptor=MyCustomErrorStatsServiceInterceptor()) + client = ErrorStatsServiceClient(transport=transport) + + + """ + + def pre_delete_events( + self, + request: error_stats_service.DeleteEventsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[error_stats_service.DeleteEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the ErrorStatsService server. + """ + return request, metadata + + def post_delete_events( + self, response: error_stats_service.DeleteEventsResponse + ) -> error_stats_service.DeleteEventsResponse: + """Post-rpc interceptor for delete_events + + Override in a subclass to manipulate the response + after it is returned by the ErrorStatsService server but before + it is returned to user code. + """ + return response + + def pre_list_events( + self, + request: error_stats_service.ListEventsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[error_stats_service.ListEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the ErrorStatsService server. + """ + return request, metadata + + def post_list_events( + self, response: error_stats_service.ListEventsResponse + ) -> error_stats_service.ListEventsResponse: + """Post-rpc interceptor for list_events + + Override in a subclass to manipulate the response + after it is returned by the ErrorStatsService server but before + it is returned to user code. + """ + return response + + def pre_list_group_stats( + self, + request: error_stats_service.ListGroupStatsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[error_stats_service.ListGroupStatsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_group_stats + + Override in a subclass to manipulate the request or metadata + before they are sent to the ErrorStatsService server. + """ + return request, metadata + + def post_list_group_stats( + self, response: error_stats_service.ListGroupStatsResponse + ) -> error_stats_service.ListGroupStatsResponse: + """Post-rpc interceptor for list_group_stats + + Override in a subclass to manipulate the response + after it is returned by the ErrorStatsService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ErrorStatsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ErrorStatsServiceRestInterceptor + + +class ErrorStatsServiceRestTransport(ErrorStatsServiceTransport): + """REST backend transport for ErrorStatsService. + + An API for retrieving and managing error statistics as well + as data for individual events. + + 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 = "clouderrorreporting.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[ErrorStatsServiceRestInterceptor] = 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 ErrorStatsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DeleteEvents(ErrorStatsServiceRestStub): + def __hash__(self): + return hash("DeleteEvents") + + __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: error_stats_service.DeleteEventsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> error_stats_service.DeleteEventsResponse: + r"""Call the delete events method over HTTP. + + Args: + request (~.error_stats_service.DeleteEventsRequest): + The request object. Deletes all events in the project. + 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: + ~.error_stats_service.DeleteEventsResponse: + Response message for deleting error + events. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{project_name=projects/*}/events", + }, + ] + request, metadata = self._interceptor.pre_delete_events(request, metadata) + pb_request = error_stats_service.DeleteEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + 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), + ) + + # 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 = error_stats_service.DeleteEventsResponse() + pb_resp = error_stats_service.DeleteEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_events(resp) + return resp + + class _ListEvents(ErrorStatsServiceRestStub): + def __hash__(self): + return hash("ListEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "groupId": "", + } + + @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: error_stats_service.ListEventsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> error_stats_service.ListEventsResponse: + r"""Call the list events method over HTTP. + + Args: + request (~.error_stats_service.ListEventsRequest): + The request object. Specifies a set of error events to + return. + + 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: + ~.error_stats_service.ListEventsResponse: + Contains a set of requested error + events. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{project_name=projects/*}/events", + }, + ] + request, metadata = self._interceptor.pre_list_events(request, metadata) + pb_request = error_stats_service.ListEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + 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), + ) + + # 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 = error_stats_service.ListEventsResponse() + pb_resp = error_stats_service.ListEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_events(resp) + return resp + + class _ListGroupStats(ErrorStatsServiceRestStub): + def __hash__(self): + return hash("ListGroupStats") + + __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: error_stats_service.ListGroupStatsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> error_stats_service.ListGroupStatsResponse: + r"""Call the list group stats method over HTTP. + + Args: + request (~.error_stats_service.ListGroupStatsRequest): + The request object. Specifies a set of ``ErrorGroupStats`` to return. + 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: + ~.error_stats_service.ListGroupStatsResponse: + Contains a set of requested error + group stats. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{project_name=projects/*}/groupStats", + }, + ] + request, metadata = self._interceptor.pre_list_group_stats( + request, metadata + ) + pb_request = error_stats_service.ListGroupStatsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + 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), + ) + + # 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 = error_stats_service.ListGroupStatsResponse() + pb_resp = error_stats_service.ListGroupStatsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_group_stats(resp) + return resp + + @property + def delete_events( + self, + ) -> Callable[ + [error_stats_service.DeleteEventsRequest], + error_stats_service.DeleteEventsResponse, + ]: + # 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._DeleteEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_events( + self, + ) -> Callable[ + [error_stats_service.ListEventsRequest], error_stats_service.ListEventsResponse + ]: + # 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._ListEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_group_stats( + self, + ) -> Callable[ + [error_stats_service.ListGroupStatsRequest], + error_stats_service.ListGroupStatsResponse, + ]: + # 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._ListGroupStats(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ErrorStatsServiceRestTransport",) diff --git a/google/cloud/errorreporting_v1beta1/services/report_errors_service/client.py b/google/cloud/errorreporting_v1beta1/services/report_errors_service/client.py index a7883f1f..f2d057b0 100644 --- a/google/cloud/errorreporting_v1beta1/services/report_errors_service/client.py +++ b/google/cloud/errorreporting_v1beta1/services/report_errors_service/client.py @@ -50,6 +50,7 @@ from .transports.base import ReportErrorsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ReportErrorsServiceGrpcTransport from .transports.grpc_asyncio import ReportErrorsServiceGrpcAsyncIOTransport +from .transports.rest import ReportErrorsServiceRestTransport class ReportErrorsServiceClientMeta(type): @@ -65,6 +66,7 @@ class ReportErrorsServiceClientMeta(type): ) # type: Dict[str, Type[ReportErrorsServiceTransport]] _transport_registry["grpc"] = ReportErrorsServiceGrpcTransport _transport_registry["grpc_asyncio"] = ReportErrorsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ReportErrorsServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/errorreporting_v1beta1/services/report_errors_service/transports/__init__.py b/google/cloud/errorreporting_v1beta1/services/report_errors_service/transports/__init__.py index b96eb345..289d0ff1 100644 --- a/google/cloud/errorreporting_v1beta1/services/report_errors_service/transports/__init__.py +++ b/google/cloud/errorreporting_v1beta1/services/report_errors_service/transports/__init__.py @@ -19,6 +19,8 @@ from .base import ReportErrorsServiceTransport from .grpc import ReportErrorsServiceGrpcTransport from .grpc_asyncio import ReportErrorsServiceGrpcAsyncIOTransport +from .rest import ReportErrorsServiceRestTransport +from .rest import ReportErrorsServiceRestInterceptor # Compile a registry of transports. @@ -27,9 +29,12 @@ ) # type: Dict[str, Type[ReportErrorsServiceTransport]] _transport_registry["grpc"] = ReportErrorsServiceGrpcTransport _transport_registry["grpc_asyncio"] = ReportErrorsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = ReportErrorsServiceRestTransport __all__ = ( "ReportErrorsServiceTransport", "ReportErrorsServiceGrpcTransport", "ReportErrorsServiceGrpcAsyncIOTransport", + "ReportErrorsServiceRestTransport", + "ReportErrorsServiceRestInterceptor", ) diff --git a/google/cloud/errorreporting_v1beta1/services/report_errors_service/transports/rest.py b/google/cloud/errorreporting_v1beta1/services/report_errors_service/transports/rest.py new file mode 100644 index 00000000..cf238616 --- /dev/null +++ b/google/cloud/errorreporting_v1beta1/services/report_errors_service/transports/rest.py @@ -0,0 +1,329 @@ +# -*- 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.errorreporting_v1beta1.types import report_errors_service + +from .base import ( + ReportErrorsServiceTransport, + DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO, +) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ReportErrorsServiceRestInterceptor: + """Interceptor for ReportErrorsService. + + 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 ReportErrorsServiceRestTransport. + + .. code-block:: python + class MyCustomReportErrorsServiceInterceptor(ReportErrorsServiceRestInterceptor): + def pre_report_error_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_report_error_event(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ReportErrorsServiceRestTransport(interceptor=MyCustomReportErrorsServiceInterceptor()) + client = ReportErrorsServiceClient(transport=transport) + + + """ + + def pre_report_error_event( + self, + request: report_errors_service.ReportErrorEventRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + report_errors_service.ReportErrorEventRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for report_error_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReportErrorsService server. + """ + return request, metadata + + def post_report_error_event( + self, response: report_errors_service.ReportErrorEventResponse + ) -> report_errors_service.ReportErrorEventResponse: + """Post-rpc interceptor for report_error_event + + Override in a subclass to manipulate the response + after it is returned by the ReportErrorsService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ReportErrorsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ReportErrorsServiceRestInterceptor + + +class ReportErrorsServiceRestTransport(ReportErrorsServiceTransport): + """REST backend transport for ReportErrorsService. + + An API for reporting error events. + + 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 = "clouderrorreporting.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[ReportErrorsServiceRestInterceptor] = 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 ReportErrorsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ReportErrorEvent(ReportErrorsServiceRestStub): + def __hash__(self): + return hash("ReportErrorEvent") + + __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: report_errors_service.ReportErrorEventRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> report_errors_service.ReportErrorEventResponse: + r"""Call the report error event method over HTTP. + + Args: + request (~.report_errors_service.ReportErrorEventRequest): + The request object. A request for reporting an individual + error event. + + 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: + ~.report_errors_service.ReportErrorEventResponse: + Response for reporting an individual + error event. Data may be added to this + message in the future. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{project_name=projects/*}/events:report", + "body": "event", + }, + ] + request, metadata = self._interceptor.pre_report_error_event( + request, metadata + ) + pb_request = report_errors_service.ReportErrorEventRequest.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 = report_errors_service.ReportErrorEventResponse() + pb_resp = report_errors_service.ReportErrorEventResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_report_error_event(resp) + return resp + + @property + def report_error_event( + self, + ) -> Callable[ + [report_errors_service.ReportErrorEventRequest], + report_errors_service.ReportErrorEventResponse, + ]: + # 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._ReportErrorEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ReportErrorsServiceRestTransport",) diff --git a/google/cloud/errorreporting_v1beta1/types/common.py b/google/cloud/errorreporting_v1beta1/types/common.py index 2f04117b..43ac4ba2 100644 --- a/google/cloud/errorreporting_v1beta1/types/common.py +++ b/google/cloud/errorreporting_v1beta1/types/common.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/google/cloud/errorreporting_v1beta1/types/error_group_service.py b/google/cloud/errorreporting_v1beta1/types/error_group_service.py index a3afd595..63ecabf9 100644 --- a/google/cloud/errorreporting_v1beta1/types/error_group_service.py +++ b/google/cloud/errorreporting_v1beta1/types/error_group_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/google/cloud/errorreporting_v1beta1/types/error_stats_service.py b/google/cloud/errorreporting_v1beta1/types/error_stats_service.py index 60d0f90a..afb2668a 100644 --- a/google/cloud/errorreporting_v1beta1/types/error_stats_service.py +++ b/google/cloud/errorreporting_v1beta1/types/error_stats_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/google/cloud/errorreporting_v1beta1/types/report_errors_service.py b/google/cloud/errorreporting_v1beta1/types/report_errors_service.py index e154c5fe..a3087c1a 100644 --- a/google/cloud/errorreporting_v1beta1/types/report_errors_service.py +++ b/google/cloud/errorreporting_v1beta1/types/report_errors_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/samples/generated_samples/snippet_metadata_google.devtools.clouderrorreporting.v1beta1.json b/samples/generated_samples/snippet_metadata_google.devtools.clouderrorreporting.v1beta1.json index 9a89b962..fedd655c 100644 --- a/samples/generated_samples/snippet_metadata_google.devtools.clouderrorreporting.v1beta1.json +++ b/samples/generated_samples/snippet_metadata_google.devtools.clouderrorreporting.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-error-reporting", - "version": "1.8.2" + "version": "0.1.0" }, "snippets": [ { diff --git a/tests/unit/gapic/errorreporting_v1beta1/test_error_group_service.py b/tests/unit/gapic/errorreporting_v1beta1/test_error_group_service.py index 994c484c..90643d98 100644 --- a/tests/unit/gapic/errorreporting_v1beta1/test_error_group_service.py +++ b/tests/unit/gapic/errorreporting_v1beta1/test_error_group_service.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -100,6 +107,7 @@ def test__get_default_mtls_endpoint(): [ (ErrorGroupServiceClient, "grpc"), (ErrorGroupServiceAsyncClient, "grpc_asyncio"), + (ErrorGroupServiceClient, "rest"), ], ) def test_error_group_service_client_from_service_account_info( @@ -115,7 +123,11 @@ def test_error_group_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("clouderrorreporting.googleapis.com:443") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com" + ) @pytest.mark.parametrize( @@ -123,6 +135,7 @@ def test_error_group_service_client_from_service_account_info( [ (transports.ErrorGroupServiceGrpcTransport, "grpc"), (transports.ErrorGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ErrorGroupServiceRestTransport, "rest"), ], ) def test_error_group_service_client_service_account_always_use_jwt( @@ -148,6 +161,7 @@ def test_error_group_service_client_service_account_always_use_jwt( [ (ErrorGroupServiceClient, "grpc"), (ErrorGroupServiceAsyncClient, "grpc_asyncio"), + (ErrorGroupServiceClient, "rest"), ], ) def test_error_group_service_client_from_service_account_file( @@ -170,13 +184,18 @@ def test_error_group_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("clouderrorreporting.googleapis.com:443") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com" + ) def test_error_group_service_client_get_transport_class(): transport = ErrorGroupServiceClient.get_transport_class() available_transports = [ transports.ErrorGroupServiceGrpcTransport, + transports.ErrorGroupServiceRestTransport, ] assert transport in available_transports @@ -193,6 +212,7 @@ def test_error_group_service_client_get_transport_class(): transports.ErrorGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (ErrorGroupServiceClient, transports.ErrorGroupServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -348,6 +368,18 @@ def test_error_group_service_client_client_options( "grpc_asyncio", "false", ), + ( + ErrorGroupServiceClient, + transports.ErrorGroupServiceRestTransport, + "rest", + "true", + ), + ( + ErrorGroupServiceClient, + transports.ErrorGroupServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -547,6 +579,7 @@ def test_error_group_service_client_get_mtls_endpoint_and_cert_source(client_cla transports.ErrorGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (ErrorGroupServiceClient, transports.ErrorGroupServiceRestTransport, "rest"), ], ) def test_error_group_service_client_client_options_scopes( @@ -587,6 +620,12 @@ def test_error_group_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + ErrorGroupServiceClient, + transports.ErrorGroupServiceRestTransport, + "rest", + None, + ), ], ) def test_error_group_service_client_client_options_credentials_file( @@ -1171,6 +1210,552 @@ async def test_update_group_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + error_group_service.GetGroupRequest, + dict, + ], +) +def test_get_group_rest(request_type): + client = ErrorGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"group_name": "projects/sample1/groups/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 = common.ErrorGroup( + name="name_value", + group_id="group_id_value", + resolution_status=common.ResolutionStatus.OPEN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = common.ErrorGroup.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.get_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, common.ErrorGroup) + assert response.name == "name_value" + assert response.group_id == "group_id_value" + assert response.resolution_status == common.ResolutionStatus.OPEN + + +def test_get_group_rest_required_fields( + request_type=error_group_service.GetGroupRequest, +): + transport_class = transports.ErrorGroupServiceRestTransport + + request_init = {} + request_init["group_name"] = "" + 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() + ).get_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["groupName"] = "group_name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "groupName" in jsonified_request + assert jsonified_request["groupName"] == "group_name_value" + + client = ErrorGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = common.ErrorGroup() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = common.ErrorGroup.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.get_group(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_group_rest_unset_required_fields(): + transport = transports.ErrorGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("groupName",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_group_rest_interceptors(null_interceptor): + transport = transports.ErrorGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ErrorGroupServiceRestInterceptor(), + ) + client = ErrorGroupServiceClient(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.ErrorGroupServiceRestInterceptor, "post_get_group" + ) as post, mock.patch.object( + transports.ErrorGroupServiceRestInterceptor, "pre_get_group" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = error_group_service.GetGroupRequest.pb( + error_group_service.GetGroupRequest() + ) + 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 = common.ErrorGroup.to_json(common.ErrorGroup()) + + request = error_group_service.GetGroupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = common.ErrorGroup() + + client.get_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_group_rest_bad_request( + transport: str = "rest", request_type=error_group_service.GetGroupRequest +): + client = ErrorGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"group_name": "projects/sample1/groups/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_group(request) + + +def test_get_group_rest_flattened(): + client = ErrorGroupServiceClient( + 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 = common.ErrorGroup() + + # get arguments that satisfy an http rule for this method + sample_request = {"group_name": "projects/sample1/groups/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + group_name="group_name_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 = common.ErrorGroup.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.get_group(**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/{group_name=projects/*/groups/*}" % client.transport._host, + args[1], + ) + + +def test_get_group_rest_flattened_error(transport: str = "rest"): + client = ErrorGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_group( + error_group_service.GetGroupRequest(), + group_name="group_name_value", + ) + + +def test_get_group_rest_error(): + client = ErrorGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + error_group_service.UpdateGroupRequest, + dict, + ], +) +def test_update_group_rest(request_type): + client = ErrorGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"group": {"name": "projects/sample1/groups/sample2"}} + request_init["group"] = { + "name": "projects/sample1/groups/sample2", + "group_id": "group_id_value", + "tracking_issues": [{"url": "url_value"}], + "resolution_status": 1, + } + 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 = common.ErrorGroup( + name="name_value", + group_id="group_id_value", + resolution_status=common.ResolutionStatus.OPEN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = common.ErrorGroup.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.update_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, common.ErrorGroup) + assert response.name == "name_value" + assert response.group_id == "group_id_value" + assert response.resolution_status == common.ResolutionStatus.OPEN + + +def test_update_group_rest_required_fields( + request_type=error_group_service.UpdateGroupRequest, +): + transport_class = transports.ErrorGroupServiceRestTransport + + request_init = {} + 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() + ).update_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ErrorGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = common.ErrorGroup() + # 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": "put", + "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 = common.ErrorGroup.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.update_group(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_group_rest_unset_required_fields(): + transport = transports.ErrorGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("group",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_group_rest_interceptors(null_interceptor): + transport = transports.ErrorGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ErrorGroupServiceRestInterceptor(), + ) + client = ErrorGroupServiceClient(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.ErrorGroupServiceRestInterceptor, "post_update_group" + ) as post, mock.patch.object( + transports.ErrorGroupServiceRestInterceptor, "pre_update_group" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = error_group_service.UpdateGroupRequest.pb( + error_group_service.UpdateGroupRequest() + ) + 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 = common.ErrorGroup.to_json(common.ErrorGroup()) + + request = error_group_service.UpdateGroupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = common.ErrorGroup() + + client.update_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_group_rest_bad_request( + transport: str = "rest", request_type=error_group_service.UpdateGroupRequest +): + client = ErrorGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"group": {"name": "projects/sample1/groups/sample2"}} + request_init["group"] = { + "name": "projects/sample1/groups/sample2", + "group_id": "group_id_value", + "tracking_issues": [{"url": "url_value"}], + "resolution_status": 1, + } + 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.update_group(request) + + +def test_update_group_rest_flattened(): + client = ErrorGroupServiceClient( + 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 = common.ErrorGroup() + + # get arguments that satisfy an http rule for this method + sample_request = {"group": {"name": "projects/sample1/groups/sample2"}} + + # get truthy value for each flattened field + mock_args = dict( + group=common.ErrorGroup(name="name_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 = common.ErrorGroup.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.update_group(**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/{group.name=projects/*/groups/*}" % client.transport._host, + args[1], + ) + + +def test_update_group_rest_flattened_error(transport: str = "rest"): + client = ErrorGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_group( + error_group_service.UpdateGroupRequest(), + group=common.ErrorGroup(name="name_value"), + ) + + +def test_update_group_rest_error(): + client = ErrorGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ErrorGroupServiceGrpcTransport( @@ -1252,6 +1837,7 @@ def test_transport_get_channel(): [ transports.ErrorGroupServiceGrpcTransport, transports.ErrorGroupServiceGrpcAsyncIOTransport, + transports.ErrorGroupServiceRestTransport, ], ) def test_transport_adc(transport_class): @@ -1266,6 +1852,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1396,6 +1983,7 @@ def test_error_group_service_transport_auth_adc(transport_class): [ transports.ErrorGroupServiceGrpcTransport, transports.ErrorGroupServiceGrpcAsyncIOTransport, + transports.ErrorGroupServiceRestTransport, ], ) def test_error_group_service_transport_auth_gdch_credentials(transport_class): @@ -1495,11 +2083,23 @@ def test_error_group_service_grpc_transport_client_cert_source_for_mtls( ) +def test_error_group_service_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.ErrorGroupServiceRestTransport( + 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_error_group_service_host_no_port(transport_name): @@ -1510,7 +2110,11 @@ def test_error_group_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("clouderrorreporting.googleapis.com:443") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com" + ) @pytest.mark.parametrize( @@ -1518,6 +2122,7 @@ def test_error_group_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_error_group_service_host_with_port(transport_name): @@ -1528,7 +2133,36 @@ def test_error_group_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("clouderrorreporting.googleapis.com:8000") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_error_group_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ErrorGroupServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ErrorGroupServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_group._session + session2 = client2.transport.get_group._session + assert session1 != session2 + session1 = client1.transport.update_group._session + session2 = client2.transport.update_group._session + assert session1 != session2 def test_error_group_service_grpc_transport_channel(): @@ -1822,6 +2456,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -1839,6 +2474,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/errorreporting_v1beta1/test_error_stats_service.py b/tests/unit/gapic/errorreporting_v1beta1/test_error_stats_service.py index c5fbcf64..4ea47201 100644 --- a/tests/unit/gapic/errorreporting_v1beta1/test_error_stats_service.py +++ b/tests/unit/gapic/errorreporting_v1beta1/test_error_stats_service.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -103,6 +110,7 @@ def test__get_default_mtls_endpoint(): [ (ErrorStatsServiceClient, "grpc"), (ErrorStatsServiceAsyncClient, "grpc_asyncio"), + (ErrorStatsServiceClient, "rest"), ], ) def test_error_stats_service_client_from_service_account_info( @@ -118,7 +126,11 @@ def test_error_stats_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("clouderrorreporting.googleapis.com:443") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com" + ) @pytest.mark.parametrize( @@ -126,6 +138,7 @@ def test_error_stats_service_client_from_service_account_info( [ (transports.ErrorStatsServiceGrpcTransport, "grpc"), (transports.ErrorStatsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ErrorStatsServiceRestTransport, "rest"), ], ) def test_error_stats_service_client_service_account_always_use_jwt( @@ -151,6 +164,7 @@ def test_error_stats_service_client_service_account_always_use_jwt( [ (ErrorStatsServiceClient, "grpc"), (ErrorStatsServiceAsyncClient, "grpc_asyncio"), + (ErrorStatsServiceClient, "rest"), ], ) def test_error_stats_service_client_from_service_account_file( @@ -173,13 +187,18 @@ def test_error_stats_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("clouderrorreporting.googleapis.com:443") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com" + ) def test_error_stats_service_client_get_transport_class(): transport = ErrorStatsServiceClient.get_transport_class() available_transports = [ transports.ErrorStatsServiceGrpcTransport, + transports.ErrorStatsServiceRestTransport, ] assert transport in available_transports @@ -196,6 +215,7 @@ def test_error_stats_service_client_get_transport_class(): transports.ErrorStatsServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (ErrorStatsServiceClient, transports.ErrorStatsServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -351,6 +371,18 @@ def test_error_stats_service_client_client_options( "grpc_asyncio", "false", ), + ( + ErrorStatsServiceClient, + transports.ErrorStatsServiceRestTransport, + "rest", + "true", + ), + ( + ErrorStatsServiceClient, + transports.ErrorStatsServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -550,6 +582,7 @@ def test_error_stats_service_client_get_mtls_endpoint_and_cert_source(client_cla transports.ErrorStatsServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (ErrorStatsServiceClient, transports.ErrorStatsServiceRestTransport, "rest"), ], ) def test_error_stats_service_client_client_options_scopes( @@ -590,6 +623,12 @@ def test_error_stats_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + ErrorStatsServiceClient, + transports.ErrorStatsServiceRestTransport, + "rest", + None, + ), ], ) def test_error_stats_service_client_client_options_credentials_file( @@ -1804,6 +1843,996 @@ async def test_delete_events_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + error_stats_service.ListGroupStatsRequest, + dict, + ], +) +def test_list_group_stats_rest(request_type): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project_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 = error_stats_service.ListGroupStatsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = error_stats_service.ListGroupStatsResponse.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.list_group_stats(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGroupStatsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_group_stats_rest_required_fields( + request_type=error_stats_service.ListGroupStatsRequest, +): + transport_class = transports.ErrorStatsServiceRestTransport + + request_init = {} + request_init["project_name"] = "" + 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() + ).list_group_stats._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["projectName"] = "project_name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_group_stats._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "alignment", + "alignment_time", + "group_id", + "order", + "page_size", + "page_token", + "service_filter", + "time_range", + "timed_count_duration", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "projectName" in jsonified_request + assert jsonified_request["projectName"] == "project_name_value" + + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = error_stats_service.ListGroupStatsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = error_stats_service.ListGroupStatsResponse.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.list_group_stats(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_group_stats_rest_unset_required_fields(): + transport = transports.ErrorStatsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_group_stats._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "alignment", + "alignmentTime", + "groupId", + "order", + "pageSize", + "pageToken", + "serviceFilter", + "timeRange", + "timedCountDuration", + ) + ) + & set(("projectName",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_group_stats_rest_interceptors(null_interceptor): + transport = transports.ErrorStatsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ErrorStatsServiceRestInterceptor(), + ) + client = ErrorStatsServiceClient(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.ErrorStatsServiceRestInterceptor, "post_list_group_stats" + ) as post, mock.patch.object( + transports.ErrorStatsServiceRestInterceptor, "pre_list_group_stats" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = error_stats_service.ListGroupStatsRequest.pb( + error_stats_service.ListGroupStatsRequest() + ) + 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 = error_stats_service.ListGroupStatsResponse.to_json( + error_stats_service.ListGroupStatsResponse() + ) + + request = error_stats_service.ListGroupStatsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = error_stats_service.ListGroupStatsResponse() + + client.list_group_stats( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_group_stats_rest_bad_request( + transport: str = "rest", request_type=error_stats_service.ListGroupStatsRequest +): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project_name": "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.list_group_stats(request) + + +def test_list_group_stats_rest_flattened(): + client = ErrorStatsServiceClient( + 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 = error_stats_service.ListGroupStatsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project_name": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project_name="project_name_value", + time_range=error_stats_service.QueryTimeRange( + period=error_stats_service.QueryTimeRange.Period.PERIOD_1_HOUR + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = error_stats_service.ListGroupStatsResponse.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.list_group_stats(**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/{project_name=projects/*}/groupStats" % client.transport._host, + args[1], + ) + + +def test_list_group_stats_rest_flattened_error(transport: str = "rest"): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_group_stats( + error_stats_service.ListGroupStatsRequest(), + project_name="project_name_value", + time_range=error_stats_service.QueryTimeRange( + period=error_stats_service.QueryTimeRange.Period.PERIOD_1_HOUR + ), + ) + + +def test_list_group_stats_rest_pager(transport: str = "rest"): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + error_stats_service.ListGroupStatsResponse( + error_group_stats=[ + error_stats_service.ErrorGroupStats(), + error_stats_service.ErrorGroupStats(), + error_stats_service.ErrorGroupStats(), + ], + next_page_token="abc", + ), + error_stats_service.ListGroupStatsResponse( + error_group_stats=[], + next_page_token="def", + ), + error_stats_service.ListGroupStatsResponse( + error_group_stats=[ + error_stats_service.ErrorGroupStats(), + ], + next_page_token="ghi", + ), + error_stats_service.ListGroupStatsResponse( + error_group_stats=[ + error_stats_service.ErrorGroupStats(), + error_stats_service.ErrorGroupStats(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + error_stats_service.ListGroupStatsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"project_name": "projects/sample1"} + + pager = client.list_group_stats(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, error_stats_service.ErrorGroupStats) for i in results) + + pages = list(client.list_group_stats(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + error_stats_service.ListEventsRequest, + dict, + ], +) +def test_list_events_rest(request_type): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project_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 = error_stats_service.ListEventsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = error_stats_service.ListEventsResponse.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.list_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_events_rest_required_fields( + request_type=error_stats_service.ListEventsRequest, +): + transport_class = transports.ErrorStatsServiceRestTransport + + request_init = {} + request_init["project_name"] = "" + request_init["group_id"] = "" + 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 + assert "groupId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "groupId" in jsonified_request + assert jsonified_request["groupId"] == request_init["group_id"] + + jsonified_request["projectName"] = "project_name_value" + jsonified_request["groupId"] = "group_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "group_id", + "page_size", + "page_token", + "service_filter", + "time_range", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "projectName" in jsonified_request + assert jsonified_request["projectName"] == "project_name_value" + assert "groupId" in jsonified_request + assert jsonified_request["groupId"] == "group_id_value" + + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = error_stats_service.ListEventsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = error_stats_service.ListEventsResponse.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.list_events(request) + + expected_params = [ + ( + "groupId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_events_rest_unset_required_fields(): + transport = transports.ErrorStatsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_events._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "groupId", + "pageSize", + "pageToken", + "serviceFilter", + "timeRange", + ) + ) + & set( + ( + "projectName", + "groupId", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_events_rest_interceptors(null_interceptor): + transport = transports.ErrorStatsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ErrorStatsServiceRestInterceptor(), + ) + client = ErrorStatsServiceClient(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.ErrorStatsServiceRestInterceptor, "post_list_events" + ) as post, mock.patch.object( + transports.ErrorStatsServiceRestInterceptor, "pre_list_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = error_stats_service.ListEventsRequest.pb( + error_stats_service.ListEventsRequest() + ) + 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 = error_stats_service.ListEventsResponse.to_json( + error_stats_service.ListEventsResponse() + ) + + request = error_stats_service.ListEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = error_stats_service.ListEventsResponse() + + client.list_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_events_rest_bad_request( + transport: str = "rest", request_type=error_stats_service.ListEventsRequest +): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project_name": "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.list_events(request) + + +def test_list_events_rest_flattened(): + client = ErrorStatsServiceClient( + 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 = error_stats_service.ListEventsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project_name": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project_name="project_name_value", + group_id="group_id_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 = error_stats_service.ListEventsResponse.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.list_events(**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/{project_name=projects/*}/events" % client.transport._host, + args[1], + ) + + +def test_list_events_rest_flattened_error(transport: str = "rest"): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_events( + error_stats_service.ListEventsRequest(), + project_name="project_name_value", + group_id="group_id_value", + ) + + +def test_list_events_rest_pager(transport: str = "rest"): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + error_stats_service.ListEventsResponse( + error_events=[ + common.ErrorEvent(), + common.ErrorEvent(), + common.ErrorEvent(), + ], + next_page_token="abc", + ), + error_stats_service.ListEventsResponse( + error_events=[], + next_page_token="def", + ), + error_stats_service.ListEventsResponse( + error_events=[ + common.ErrorEvent(), + ], + next_page_token="ghi", + ), + error_stats_service.ListEventsResponse( + error_events=[ + common.ErrorEvent(), + common.ErrorEvent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + error_stats_service.ListEventsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"project_name": "projects/sample1"} + + pager = client.list_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, common.ErrorEvent) for i in results) + + pages = list(client.list_events(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + error_stats_service.DeleteEventsRequest, + dict, + ], +) +def test_delete_events_rest(request_type): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project_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 = error_stats_service.DeleteEventsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = error_stats_service.DeleteEventsResponse.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.delete_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, error_stats_service.DeleteEventsResponse) + + +def test_delete_events_rest_required_fields( + request_type=error_stats_service.DeleteEventsRequest, +): + transport_class = transports.ErrorStatsServiceRestTransport + + request_init = {} + request_init["project_name"] = "" + 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() + ).delete_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["projectName"] = "project_name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "projectName" in jsonified_request + assert jsonified_request["projectName"] == "project_name_value" + + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = error_stats_service.DeleteEventsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = error_stats_service.DeleteEventsResponse.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.delete_events(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_events_rest_unset_required_fields(): + transport = transports.ErrorStatsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("projectName",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_events_rest_interceptors(null_interceptor): + transport = transports.ErrorStatsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ErrorStatsServiceRestInterceptor(), + ) + client = ErrorStatsServiceClient(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.ErrorStatsServiceRestInterceptor, "post_delete_events" + ) as post, mock.patch.object( + transports.ErrorStatsServiceRestInterceptor, "pre_delete_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = error_stats_service.DeleteEventsRequest.pb( + error_stats_service.DeleteEventsRequest() + ) + 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 = error_stats_service.DeleteEventsResponse.to_json( + error_stats_service.DeleteEventsResponse() + ) + + request = error_stats_service.DeleteEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = error_stats_service.DeleteEventsResponse() + + client.delete_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_events_rest_bad_request( + transport: str = "rest", request_type=error_stats_service.DeleteEventsRequest +): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project_name": "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.delete_events(request) + + +def test_delete_events_rest_flattened(): + client = ErrorStatsServiceClient( + 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 = error_stats_service.DeleteEventsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project_name": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project_name="project_name_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 = error_stats_service.DeleteEventsResponse.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.delete_events(**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/{project_name=projects/*}/events" % client.transport._host, + args[1], + ) + + +def test_delete_events_rest_flattened_error(transport: str = "rest"): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_events( + error_stats_service.DeleteEventsRequest(), + project_name="project_name_value", + ) + + +def test_delete_events_rest_error(): + client = ErrorStatsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ErrorStatsServiceGrpcTransport( @@ -1885,6 +2914,7 @@ def test_transport_get_channel(): [ transports.ErrorStatsServiceGrpcTransport, transports.ErrorStatsServiceGrpcAsyncIOTransport, + transports.ErrorStatsServiceRestTransport, ], ) def test_transport_adc(transport_class): @@ -1899,6 +2929,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -2030,6 +3061,7 @@ def test_error_stats_service_transport_auth_adc(transport_class): [ transports.ErrorStatsServiceGrpcTransport, transports.ErrorStatsServiceGrpcAsyncIOTransport, + transports.ErrorStatsServiceRestTransport, ], ) def test_error_stats_service_transport_auth_gdch_credentials(transport_class): @@ -2129,11 +3161,23 @@ def test_error_stats_service_grpc_transport_client_cert_source_for_mtls( ) +def test_error_stats_service_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.ErrorStatsServiceRestTransport( + 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_error_stats_service_host_no_port(transport_name): @@ -2144,7 +3188,11 @@ def test_error_stats_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("clouderrorreporting.googleapis.com:443") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com" + ) @pytest.mark.parametrize( @@ -2152,6 +3200,7 @@ def test_error_stats_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_error_stats_service_host_with_port(transport_name): @@ -2162,7 +3211,39 @@ def test_error_stats_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("clouderrorreporting.googleapis.com:8000") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_error_stats_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ErrorStatsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ErrorStatsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_group_stats._session + session2 = client2.transport.list_group_stats._session + assert session1 != session2 + session1 = client1.transport.list_events._session + session2 = client2.transport.list_events._session + assert session1 != session2 + session1 = client1.transport.delete_events._session + session2 = client2.transport.delete_events._session + assert session1 != session2 def test_error_stats_service_grpc_transport_channel(): @@ -2456,6 +3537,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2473,6 +3555,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/errorreporting_v1beta1/test_report_errors_service.py b/tests/unit/gapic/errorreporting_v1beta1/test_report_errors_service.py index 85eb3987..3a69144f 100644 --- a/tests/unit/gapic/errorreporting_v1beta1/test_report_errors_service.py +++ b/tests/unit/gapic/errorreporting_v1beta1/test_report_errors_service.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -103,6 +110,7 @@ def test__get_default_mtls_endpoint(): [ (ReportErrorsServiceClient, "grpc"), (ReportErrorsServiceAsyncClient, "grpc_asyncio"), + (ReportErrorsServiceClient, "rest"), ], ) def test_report_errors_service_client_from_service_account_info( @@ -118,7 +126,11 @@ def test_report_errors_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("clouderrorreporting.googleapis.com:443") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com" + ) @pytest.mark.parametrize( @@ -126,6 +138,7 @@ def test_report_errors_service_client_from_service_account_info( [ (transports.ReportErrorsServiceGrpcTransport, "grpc"), (transports.ReportErrorsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ReportErrorsServiceRestTransport, "rest"), ], ) def test_report_errors_service_client_service_account_always_use_jwt( @@ -151,6 +164,7 @@ def test_report_errors_service_client_service_account_always_use_jwt( [ (ReportErrorsServiceClient, "grpc"), (ReportErrorsServiceAsyncClient, "grpc_asyncio"), + (ReportErrorsServiceClient, "rest"), ], ) def test_report_errors_service_client_from_service_account_file( @@ -173,13 +187,18 @@ def test_report_errors_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("clouderrorreporting.googleapis.com:443") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com" + ) def test_report_errors_service_client_get_transport_class(): transport = ReportErrorsServiceClient.get_transport_class() available_transports = [ transports.ReportErrorsServiceGrpcTransport, + transports.ReportErrorsServiceRestTransport, ] assert transport in available_transports @@ -200,6 +219,11 @@ def test_report_errors_service_client_get_transport_class(): transports.ReportErrorsServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + ReportErrorsServiceClient, + transports.ReportErrorsServiceRestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -355,6 +379,18 @@ def test_report_errors_service_client_client_options( "grpc_asyncio", "false", ), + ( + ReportErrorsServiceClient, + transports.ReportErrorsServiceRestTransport, + "rest", + "true", + ), + ( + ReportErrorsServiceClient, + transports.ReportErrorsServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -558,6 +594,11 @@ def test_report_errors_service_client_get_mtls_endpoint_and_cert_source(client_c transports.ReportErrorsServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + ReportErrorsServiceClient, + transports.ReportErrorsServiceRestTransport, + "rest", + ), ], ) def test_report_errors_service_client_client_options_scopes( @@ -598,6 +639,12 @@ def test_report_errors_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + ReportErrorsServiceClient, + transports.ReportErrorsServiceRestTransport, + "rest", + None, + ), ], ) def test_report_errors_service_client_client_options_credentials_file( @@ -973,6 +1020,344 @@ async def test_report_error_event_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + report_errors_service.ReportErrorEventRequest, + dict, + ], +) +def test_report_error_event_rest(request_type): + client = ReportErrorsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project_name": "projects/sample1"} + request_init["event"] = { + "event_time": {"seconds": 751, "nanos": 543}, + "service_context": { + "service": "service_value", + "version": "version_value", + "resource_type": "resource_type_value", + }, + "message": "message_value", + "context": { + "http_request": { + "method": "method_value", + "url": "url_value", + "user_agent": "user_agent_value", + "referrer": "referrer_value", + "response_status_code": 2156, + "remote_ip": "remote_ip_value", + }, + "user": "user_value", + "report_location": { + "file_path": "file_path_value", + "line_number": 1168, + "function_name": "function_name_value", + }, + }, + } + 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 = report_errors_service.ReportErrorEventResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = report_errors_service.ReportErrorEventResponse.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_error_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, report_errors_service.ReportErrorEventResponse) + + +def test_report_error_event_rest_required_fields( + request_type=report_errors_service.ReportErrorEventRequest, +): + transport_class = transports.ReportErrorsServiceRestTransport + + request_init = {} + request_init["project_name"] = "" + 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_error_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["projectName"] = "project_name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_error_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "projectName" in jsonified_request + assert jsonified_request["projectName"] == "project_name_value" + + client = ReportErrorsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = report_errors_service.ReportErrorEventResponse() + # 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 = report_errors_service.ReportErrorEventResponse.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_error_event(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_report_error_event_rest_unset_required_fields(): + transport = transports.ReportErrorsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.report_error_event._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "projectName", + "event", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_report_error_event_rest_interceptors(null_interceptor): + transport = transports.ReportErrorsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReportErrorsServiceRestInterceptor(), + ) + client = ReportErrorsServiceClient(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.ReportErrorsServiceRestInterceptor, "post_report_error_event" + ) as post, mock.patch.object( + transports.ReportErrorsServiceRestInterceptor, "pre_report_error_event" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = report_errors_service.ReportErrorEventRequest.pb( + report_errors_service.ReportErrorEventRequest() + ) + 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 = ( + report_errors_service.ReportErrorEventResponse.to_json( + report_errors_service.ReportErrorEventResponse() + ) + ) + + request = report_errors_service.ReportErrorEventRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = report_errors_service.ReportErrorEventResponse() + + client.report_error_event( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_report_error_event_rest_bad_request( + transport: str = "rest", request_type=report_errors_service.ReportErrorEventRequest +): + client = ReportErrorsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project_name": "projects/sample1"} + request_init["event"] = { + "event_time": {"seconds": 751, "nanos": 543}, + "service_context": { + "service": "service_value", + "version": "version_value", + "resource_type": "resource_type_value", + }, + "message": "message_value", + "context": { + "http_request": { + "method": "method_value", + "url": "url_value", + "user_agent": "user_agent_value", + "referrer": "referrer_value", + "response_status_code": 2156, + "remote_ip": "remote_ip_value", + }, + "user": "user_value", + "report_location": { + "file_path": "file_path_value", + "line_number": 1168, + "function_name": "function_name_value", + }, + }, + } + 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_error_event(request) + + +def test_report_error_event_rest_flattened(): + client = ReportErrorsServiceClient( + 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 = report_errors_service.ReportErrorEventResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project_name": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project_name="project_name_value", + event=report_errors_service.ReportedErrorEvent( + event_time=timestamp_pb2.Timestamp(seconds=751) + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = report_errors_service.ReportErrorEventResponse.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_error_event(**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/{project_name=projects/*}/events:report" + % client.transport._host, + args[1], + ) + + +def test_report_error_event_rest_flattened_error(transport: str = "rest"): + client = ReportErrorsServiceClient( + 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_error_event( + report_errors_service.ReportErrorEventRequest(), + project_name="project_name_value", + event=report_errors_service.ReportedErrorEvent( + event_time=timestamp_pb2.Timestamp(seconds=751) + ), + ) + + +def test_report_error_event_rest_error(): + client = ReportErrorsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ReportErrorsServiceGrpcTransport( @@ -1054,6 +1439,7 @@ def test_transport_get_channel(): [ transports.ReportErrorsServiceGrpcTransport, transports.ReportErrorsServiceGrpcAsyncIOTransport, + transports.ReportErrorsServiceRestTransport, ], ) def test_transport_adc(transport_class): @@ -1068,6 +1454,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1195,6 +1582,7 @@ def test_report_errors_service_transport_auth_adc(transport_class): [ transports.ReportErrorsServiceGrpcTransport, transports.ReportErrorsServiceGrpcAsyncIOTransport, + transports.ReportErrorsServiceRestTransport, ], ) def test_report_errors_service_transport_auth_gdch_credentials(transport_class): @@ -1294,11 +1682,23 @@ def test_report_errors_service_grpc_transport_client_cert_source_for_mtls( ) +def test_report_errors_service_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.ReportErrorsServiceRestTransport( + 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_report_errors_service_host_no_port(transport_name): @@ -1309,7 +1709,11 @@ def test_report_errors_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("clouderrorreporting.googleapis.com:443") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com" + ) @pytest.mark.parametrize( @@ -1317,6 +1721,7 @@ def test_report_errors_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_report_errors_service_host_with_port(transport_name): @@ -1327,7 +1732,33 @@ def test_report_errors_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("clouderrorreporting.googleapis.com:8000") + assert client.transport._host == ( + "clouderrorreporting.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://clouderrorreporting.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_report_errors_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ReportErrorsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ReportErrorsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.report_error_event._session + session2 = client2.transport.report_error_event._session + assert session1 != session2 def test_report_errors_service_grpc_transport_channel(): @@ -1598,6 +2029,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -1615,6 +2047,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: