From bab8b4cdfd71d9ee7c9181d054c287f5d051e2a7 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 16 Feb 2023 15:28:58 -0500 Subject: [PATCH] feat: enable "rest" transport in Python for services supporting numeric enums (#257) 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 --------- Co-authored-by: Owl Bot --- .../gapic_metadata.json | 30 + .../services/dashboards_service/client.py | 2 + .../dashboards_service/transports/__init__.py | 5 + .../dashboards_service/transports/rest.py | 821 ++++++++ .../test_dashboards_service.py | 1775 ++++++++++++++++- 5 files changed, 2629 insertions(+), 4 deletions(-) create mode 100644 google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/rest.py diff --git a/google/cloud/monitoring_dashboard_v1/gapic_metadata.json b/google/cloud/monitoring_dashboard_v1/gapic_metadata.json index c21b158..f7aa2bf 100644 --- a/google/cloud/monitoring_dashboard_v1/gapic_metadata.json +++ b/google/cloud/monitoring_dashboard_v1/gapic_metadata.json @@ -66,6 +66,36 @@ ] } } + }, + "rest": { + "libraryClient": "DashboardsServiceClient", + "rpcs": { + "CreateDashboard": { + "methods": [ + "create_dashboard" + ] + }, + "DeleteDashboard": { + "methods": [ + "delete_dashboard" + ] + }, + "GetDashboard": { + "methods": [ + "get_dashboard" + ] + }, + "ListDashboards": { + "methods": [ + "list_dashboards" + ] + }, + "UpdateDashboard": { + "methods": [ + "update_dashboard" + ] + } + } } } } diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/client.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/client.py index fd7e65b..a589cf5 100644 --- a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/client.py +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/client.py @@ -54,6 +54,7 @@ from .transports.base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import DashboardsServiceGrpcTransport from .transports.grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport +from .transports.rest import DashboardsServiceRestTransport class DashboardsServiceClientMeta(type): @@ -69,6 +70,7 @@ class DashboardsServiceClientMeta(type): ) # type: Dict[str, Type[DashboardsServiceTransport]] _transport_registry["grpc"] = DashboardsServiceGrpcTransport _transport_registry["grpc_asyncio"] = DashboardsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DashboardsServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/__init__.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/__init__.py index 29125e1..cf42901 100644 --- a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/__init__.py +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/__init__.py @@ -19,15 +19,20 @@ from .base import DashboardsServiceTransport from .grpc import DashboardsServiceGrpcTransport from .grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport +from .rest import DashboardsServiceRestTransport +from .rest import DashboardsServiceRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[DashboardsServiceTransport]] _transport_registry["grpc"] = DashboardsServiceGrpcTransport _transport_registry["grpc_asyncio"] = DashboardsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = DashboardsServiceRestTransport __all__ = ( "DashboardsServiceTransport", "DashboardsServiceGrpcTransport", "DashboardsServiceGrpcAsyncIOTransport", + "DashboardsServiceRestTransport", + "DashboardsServiceRestInterceptor", ) diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/rest.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/rest.py new file mode 100644 index 0000000..e3cda40 --- /dev/null +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/rest.py @@ -0,0 +1,821 @@ +# -*- 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 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.monitoring_dashboard_v1.types import dashboard +from google.cloud.monitoring_dashboard_v1.types import dashboards_service +from google.protobuf import empty_pb2 # type: ignore + +from .base import ( + DashboardsServiceTransport, + 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 DashboardsServiceRestInterceptor: + """Interceptor for DashboardsService. + + 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 DashboardsServiceRestTransport. + + .. code-block:: python + class MyCustomDashboardsServiceInterceptor(DashboardsServiceRestInterceptor): + def pre_create_dashboard(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_dashboard(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_dashboard(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_dashboard(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_dashboard(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_dashboards(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_dashboards(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_dashboard(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_dashboard(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DashboardsServiceRestTransport(interceptor=MyCustomDashboardsServiceInterceptor()) + client = DashboardsServiceClient(transport=transport) + + + """ + + def pre_create_dashboard( + self, + request: dashboards_service.CreateDashboardRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dashboards_service.CreateDashboardRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_dashboard + + Override in a subclass to manipulate the request or metadata + before they are sent to the DashboardsService server. + """ + return request, metadata + + def post_create_dashboard( + self, response: dashboard.Dashboard + ) -> dashboard.Dashboard: + """Post-rpc interceptor for create_dashboard + + Override in a subclass to manipulate the response + after it is returned by the DashboardsService server but before + it is returned to user code. + """ + return response + + def pre_delete_dashboard( + self, + request: dashboards_service.DeleteDashboardRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dashboards_service.DeleteDashboardRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_dashboard + + Override in a subclass to manipulate the request or metadata + before they are sent to the DashboardsService server. + """ + return request, metadata + + def pre_get_dashboard( + self, + request: dashboards_service.GetDashboardRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dashboards_service.GetDashboardRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_dashboard + + Override in a subclass to manipulate the request or metadata + before they are sent to the DashboardsService server. + """ + return request, metadata + + def post_get_dashboard(self, response: dashboard.Dashboard) -> dashboard.Dashboard: + """Post-rpc interceptor for get_dashboard + + Override in a subclass to manipulate the response + after it is returned by the DashboardsService server but before + it is returned to user code. + """ + return response + + def pre_list_dashboards( + self, + request: dashboards_service.ListDashboardsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dashboards_service.ListDashboardsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_dashboards + + Override in a subclass to manipulate the request or metadata + before they are sent to the DashboardsService server. + """ + return request, metadata + + def post_list_dashboards( + self, response: dashboards_service.ListDashboardsResponse + ) -> dashboards_service.ListDashboardsResponse: + """Post-rpc interceptor for list_dashboards + + Override in a subclass to manipulate the response + after it is returned by the DashboardsService server but before + it is returned to user code. + """ + return response + + def pre_update_dashboard( + self, + request: dashboards_service.UpdateDashboardRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dashboards_service.UpdateDashboardRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_dashboard + + Override in a subclass to manipulate the request or metadata + before they are sent to the DashboardsService server. + """ + return request, metadata + + def post_update_dashboard( + self, response: dashboard.Dashboard + ) -> dashboard.Dashboard: + """Post-rpc interceptor for update_dashboard + + Override in a subclass to manipulate the response + after it is returned by the DashboardsService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DashboardsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DashboardsServiceRestInterceptor + + +class DashboardsServiceRestTransport(DashboardsServiceTransport): + """REST backend transport for DashboardsService. + + Manages Stackdriver dashboards. A dashboard is an arrangement + of data display widgets in a specific layout. + + 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 = "monitoring.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[DashboardsServiceRestInterceptor] = 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 DashboardsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateDashboard(DashboardsServiceRestStub): + def __hash__(self): + return hash("CreateDashboard") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dashboards_service.CreateDashboardRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dashboard.Dashboard: + r"""Call the create dashboard method over HTTP. + + Args: + request (~.dashboards_service.CreateDashboardRequest): + The request object. The ``CreateDashboard`` request. + 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: + ~.dashboard.Dashboard: + A Google Stackdriver dashboard. + Dashboards define the content and layout + of pages in the Stackdriver web + application. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/dashboards", + "body": "dashboard", + }, + ] + request, metadata = self._interceptor.pre_create_dashboard( + request, metadata + ) + pb_request = dashboards_service.CreateDashboardRequest.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 = dashboard.Dashboard() + pb_resp = dashboard.Dashboard.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_dashboard(resp) + return resp + + class _DeleteDashboard(DashboardsServiceRestStub): + def __hash__(self): + return hash("DeleteDashboard") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dashboards_service.DeleteDashboardRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete dashboard method over HTTP. + + Args: + request (~.dashboards_service.DeleteDashboardRequest): + The request object. The ``DeleteDashboard`` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/dashboards/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_dashboard( + request, metadata + ) + pb_request = dashboards_service.DeleteDashboardRequest.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) + + class _GetDashboard(DashboardsServiceRestStub): + def __hash__(self): + return hash("GetDashboard") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dashboards_service.GetDashboardRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dashboard.Dashboard: + r"""Call the get dashboard method over HTTP. + + Args: + request (~.dashboards_service.GetDashboardRequest): + The request object. The ``GetDashboard`` request. + 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: + ~.dashboard.Dashboard: + A Google Stackdriver dashboard. + Dashboards define the content and layout + of pages in the Stackdriver web + application. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/dashboards/*}", + }, + ] + request, metadata = self._interceptor.pre_get_dashboard(request, metadata) + pb_request = dashboards_service.GetDashboardRequest.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 = dashboard.Dashboard() + pb_resp = dashboard.Dashboard.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_dashboard(resp) + return resp + + class _ListDashboards(DashboardsServiceRestStub): + def __hash__(self): + return hash("ListDashboards") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dashboards_service.ListDashboardsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dashboards_service.ListDashboardsResponse: + r"""Call the list dashboards method over HTTP. + + Args: + request (~.dashboards_service.ListDashboardsRequest): + The request object. The ``ListDashboards`` request. + 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: + ~.dashboards_service.ListDashboardsResponse: + The ``ListDashboards`` request. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*}/dashboards", + }, + ] + request, metadata = self._interceptor.pre_list_dashboards(request, metadata) + pb_request = dashboards_service.ListDashboardsRequest.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 = dashboards_service.ListDashboardsResponse() + pb_resp = dashboards_service.ListDashboardsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_dashboards(resp) + return resp + + class _UpdateDashboard(DashboardsServiceRestStub): + def __hash__(self): + return hash("UpdateDashboard") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dashboards_service.UpdateDashboardRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dashboard.Dashboard: + r"""Call the update dashboard method over HTTP. + + Args: + request (~.dashboards_service.UpdateDashboardRequest): + The request object. The ``UpdateDashboard`` request. + 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: + ~.dashboard.Dashboard: + A Google Stackdriver dashboard. + Dashboards define the content and layout + of pages in the Stackdriver web + application. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{dashboard.name=projects/*/dashboards/*}", + "body": "dashboard", + }, + ] + request, metadata = self._interceptor.pre_update_dashboard( + request, metadata + ) + pb_request = dashboards_service.UpdateDashboardRequest.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 = dashboard.Dashboard() + pb_resp = dashboard.Dashboard.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_dashboard(resp) + return resp + + @property + def create_dashboard( + self, + ) -> Callable[[dashboards_service.CreateDashboardRequest], dashboard.Dashboard]: + # 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._CreateDashboard(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_dashboard( + self, + ) -> Callable[[dashboards_service.DeleteDashboardRequest], empty_pb2.Empty]: + # 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._DeleteDashboard(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_dashboard( + self, + ) -> Callable[[dashboards_service.GetDashboardRequest], dashboard.Dashboard]: + # 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._GetDashboard(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_dashboards( + self, + ) -> Callable[ + [dashboards_service.ListDashboardsRequest], + dashboards_service.ListDashboardsResponse, + ]: + # 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._ListDashboards(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_dashboard( + self, + ) -> Callable[[dashboards_service.UpdateDashboardRequest], dashboard.Dashboard]: + # 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._UpdateDashboard(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("DashboardsServiceRestTransport",) diff --git a/tests/unit/gapic/monitoring_dashboard_v1/test_dashboards_service.py b/tests/unit/gapic/monitoring_dashboard_v1/test_dashboards_service.py index 58d5dd7..91f0c8f 100644 --- a/tests/unit/gapic/monitoring_dashboard_v1/test_dashboards_service.py +++ b/tests/unit/gapic/monitoring_dashboard_v1/test_dashboards_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 @@ -116,6 +123,7 @@ def test__get_default_mtls_endpoint(): [ (DashboardsServiceClient, "grpc"), (DashboardsServiceAsyncClient, "grpc_asyncio"), + (DashboardsServiceClient, "rest"), ], ) def test_dashboards_service_client_from_service_account_info( @@ -131,7 +139,11 @@ def test_dashboards_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("monitoring.googleapis.com:443") + assert client.transport._host == ( + "monitoring.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://monitoring.googleapis.com" + ) @pytest.mark.parametrize( @@ -139,6 +151,7 @@ def test_dashboards_service_client_from_service_account_info( [ (transports.DashboardsServiceGrpcTransport, "grpc"), (transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DashboardsServiceRestTransport, "rest"), ], ) def test_dashboards_service_client_service_account_always_use_jwt( @@ -164,6 +177,7 @@ def test_dashboards_service_client_service_account_always_use_jwt( [ (DashboardsServiceClient, "grpc"), (DashboardsServiceAsyncClient, "grpc_asyncio"), + (DashboardsServiceClient, "rest"), ], ) def test_dashboards_service_client_from_service_account_file( @@ -186,13 +200,18 @@ def test_dashboards_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("monitoring.googleapis.com:443") + assert client.transport._host == ( + "monitoring.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://monitoring.googleapis.com" + ) def test_dashboards_service_client_get_transport_class(): transport = DashboardsServiceClient.get_transport_class() available_transports = [ transports.DashboardsServiceGrpcTransport, + transports.DashboardsServiceRestTransport, ] assert transport in available_transports @@ -209,6 +228,7 @@ def test_dashboards_service_client_get_transport_class(): transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (DashboardsServiceClient, transports.DashboardsServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -364,6 +384,18 @@ def test_dashboards_service_client_client_options( "grpc_asyncio", "false", ), + ( + DashboardsServiceClient, + transports.DashboardsServiceRestTransport, + "rest", + "true", + ), + ( + DashboardsServiceClient, + transports.DashboardsServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -563,6 +595,7 @@ def test_dashboards_service_client_get_mtls_endpoint_and_cert_source(client_clas transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (DashboardsServiceClient, transports.DashboardsServiceRestTransport, "rest"), ], ) def test_dashboards_service_client_client_options_scopes( @@ -603,6 +636,12 @@ def test_dashboards_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + DashboardsServiceClient, + transports.DashboardsServiceRestTransport, + "rest", + None, + ), ], ) def test_dashboards_service_client_client_options_credentials_file( @@ -1673,6 +1712,1674 @@ async def test_update_dashboard_field_headers_async(): ) in kw["metadata"] +@pytest.mark.parametrize( + "request_type", + [ + dashboards_service.CreateDashboardRequest, + dict, + ], +) +def test_create_dashboard_rest(request_type): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["dashboard"] = { + "name": "name_value", + "display_name": "display_name_value", + "etag": "etag_value", + "grid_layout": { + "columns": 769, + "widgets": [ + { + "title": "title_value", + "xy_chart": { + "data_sets": [ + { + "time_series_query": { + "time_series_filter": { + "filter": "filter_value", + "aggregation": { + "alignment_period": { + "seconds": 751, + "nanos": 543, + }, + "per_series_aligner": 1, + "cross_series_reducer": 1, + "group_by_fields": [ + "group_by_fields_value1", + "group_by_fields_value2", + ], + }, + "secondary_aggregation": {}, + "pick_time_series_filter": { + "ranking_method": 1, + "num_time_series": 1608, + "direction": 1, + }, + "statistical_time_series_filter": { + "ranking_method": 1, + "num_time_series": 1608, + }, + }, + "time_series_filter_ratio": { + "numerator": { + "filter": "filter_value", + "aggregation": {}, + }, + "denominator": {}, + "secondary_aggregation": {}, + "pick_time_series_filter": {}, + "statistical_time_series_filter": {}, + }, + "time_series_query_language": "time_series_query_language_value", + "prometheus_query": "prometheus_query_value", + "unit_override": "unit_override_value", + }, + "plot_type": 1, + "legend_template": "legend_template_value", + "min_alignment_period": {}, + "target_axis": 1, + } + ], + "timeshift_duration": {}, + "thresholds": [ + { + "label": "label_value", + "value": 0.541, + "color": 4, + "direction": 1, + "target_axis": 1, + } + ], + "x_axis": {"label": "label_value", "scale": 1}, + "y_axis": {}, + "y2_axis": {}, + "chart_options": {"mode": 1}, + }, + "scorecard": { + "time_series_query": {}, + "gauge_view": {"lower_bound": 0.1184, "upper_bound": 0.1187}, + "spark_chart_view": { + "spark_chart_type": 1, + "min_alignment_period": {}, + }, + "thresholds": {}, + }, + "text": {"content": "content_value", "format_": 1}, + "blank": {}, + "alert_chart": {"name": "name_value"}, + "time_series_table": { + "data_sets": [ + { + "time_series_query": {}, + "table_template": "table_template_value", + "min_alignment_period": {}, + "table_display_options": { + "shown_columns": [ + "shown_columns_value1", + "shown_columns_value2", + ] + }, + } + ], + "metric_visualization": 1, + "column_settings": [ + {"column": "column_value", "visible": True} + ], + }, + "collapsible_group": {"collapsed": True}, + "logs_panel": { + "filter": "filter_value", + "resource_names": [ + "resource_names_value1", + "resource_names_value2", + ], + }, + } + ], + }, + "mosaic_layout": { + "columns": 769, + "tiles": [ + {"x_pos": 553, "y_pos": 554, "width": 544, "height": 633, "widget": {}} + ], + }, + "row_layout": {"rows": [{"weight": 648, "widgets": {}}]}, + "column_layout": {"columns": [{"weight": 648, "widgets": {}}]}, + "dashboard_filters": [ + { + "label_key": "label_key_value", + "template_variable": "template_variable_value", + "string_value": "string_value_value", + "filter_type": 1, + } + ], + "labels": {}, + } + 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 = dashboard.Dashboard( + name="name_value", + display_name="display_name_value", + etag="etag_value", + grid_layout=layouts.GridLayout(columns=769), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dashboard.Dashboard.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.create_dashboard(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.etag == "etag_value" + + +def test_create_dashboard_rest_required_fields( + request_type=dashboards_service.CreateDashboardRequest, +): + transport_class = transports.DashboardsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_dashboard._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_dashboard._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dashboard.Dashboard() + # 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 = dashboard.Dashboard.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.create_dashboard(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_dashboard_rest_unset_required_fields(): + transport = transports.DashboardsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_dashboard._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("validateOnly",)) + & set( + ( + "parent", + "dashboard", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_dashboard_rest_interceptors(null_interceptor): + transport = transports.DashboardsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DashboardsServiceRestInterceptor(), + ) + client = DashboardsServiceClient(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.DashboardsServiceRestInterceptor, "post_create_dashboard" + ) as post, mock.patch.object( + transports.DashboardsServiceRestInterceptor, "pre_create_dashboard" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dashboards_service.CreateDashboardRequest.pb( + dashboards_service.CreateDashboardRequest() + ) + 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 = dashboard.Dashboard.to_json(dashboard.Dashboard()) + + request = dashboards_service.CreateDashboardRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dashboard.Dashboard() + + client.create_dashboard( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_dashboard_rest_bad_request( + transport: str = "rest", request_type=dashboards_service.CreateDashboardRequest +): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["dashboard"] = { + "name": "name_value", + "display_name": "display_name_value", + "etag": "etag_value", + "grid_layout": { + "columns": 769, + "widgets": [ + { + "title": "title_value", + "xy_chart": { + "data_sets": [ + { + "time_series_query": { + "time_series_filter": { + "filter": "filter_value", + "aggregation": { + "alignment_period": { + "seconds": 751, + "nanos": 543, + }, + "per_series_aligner": 1, + "cross_series_reducer": 1, + "group_by_fields": [ + "group_by_fields_value1", + "group_by_fields_value2", + ], + }, + "secondary_aggregation": {}, + "pick_time_series_filter": { + "ranking_method": 1, + "num_time_series": 1608, + "direction": 1, + }, + "statistical_time_series_filter": { + "ranking_method": 1, + "num_time_series": 1608, + }, + }, + "time_series_filter_ratio": { + "numerator": { + "filter": "filter_value", + "aggregation": {}, + }, + "denominator": {}, + "secondary_aggregation": {}, + "pick_time_series_filter": {}, + "statistical_time_series_filter": {}, + }, + "time_series_query_language": "time_series_query_language_value", + "prometheus_query": "prometheus_query_value", + "unit_override": "unit_override_value", + }, + "plot_type": 1, + "legend_template": "legend_template_value", + "min_alignment_period": {}, + "target_axis": 1, + } + ], + "timeshift_duration": {}, + "thresholds": [ + { + "label": "label_value", + "value": 0.541, + "color": 4, + "direction": 1, + "target_axis": 1, + } + ], + "x_axis": {"label": "label_value", "scale": 1}, + "y_axis": {}, + "y2_axis": {}, + "chart_options": {"mode": 1}, + }, + "scorecard": { + "time_series_query": {}, + "gauge_view": {"lower_bound": 0.1184, "upper_bound": 0.1187}, + "spark_chart_view": { + "spark_chart_type": 1, + "min_alignment_period": {}, + }, + "thresholds": {}, + }, + "text": {"content": "content_value", "format_": 1}, + "blank": {}, + "alert_chart": {"name": "name_value"}, + "time_series_table": { + "data_sets": [ + { + "time_series_query": {}, + "table_template": "table_template_value", + "min_alignment_period": {}, + "table_display_options": { + "shown_columns": [ + "shown_columns_value1", + "shown_columns_value2", + ] + }, + } + ], + "metric_visualization": 1, + "column_settings": [ + {"column": "column_value", "visible": True} + ], + }, + "collapsible_group": {"collapsed": True}, + "logs_panel": { + "filter": "filter_value", + "resource_names": [ + "resource_names_value1", + "resource_names_value2", + ], + }, + } + ], + }, + "mosaic_layout": { + "columns": 769, + "tiles": [ + {"x_pos": 553, "y_pos": 554, "width": 544, "height": 633, "widget": {}} + ], + }, + "row_layout": {"rows": [{"weight": 648, "widgets": {}}]}, + "column_layout": {"columns": [{"weight": 648, "widgets": {}}]}, + "dashboard_filters": [ + { + "label_key": "label_key_value", + "template_variable": "template_variable_value", + "string_value": "string_value_value", + "filter_type": 1, + } + ], + "labels": {}, + } + 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.create_dashboard(request) + + +def test_create_dashboard_rest_error(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dashboards_service.ListDashboardsRequest, + dict, + ], +) +def test_list_dashboards_rest(request_type): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dashboards_service.ListDashboardsResponse( + 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 = dashboards_service.ListDashboardsResponse.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_dashboards(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDashboardsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_dashboards_rest_required_fields( + request_type=dashboards_service.ListDashboardsRequest, +): + transport_class = transports.DashboardsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_dashboards._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_dashboards._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dashboards_service.ListDashboardsResponse() + # 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 = dashboards_service.ListDashboardsResponse.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_dashboards(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_dashboards_rest_unset_required_fields(): + transport = transports.DashboardsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_dashboards._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_dashboards_rest_interceptors(null_interceptor): + transport = transports.DashboardsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DashboardsServiceRestInterceptor(), + ) + client = DashboardsServiceClient(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.DashboardsServiceRestInterceptor, "post_list_dashboards" + ) as post, mock.patch.object( + transports.DashboardsServiceRestInterceptor, "pre_list_dashboards" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dashboards_service.ListDashboardsRequest.pb( + dashboards_service.ListDashboardsRequest() + ) + 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 = dashboards_service.ListDashboardsResponse.to_json( + dashboards_service.ListDashboardsResponse() + ) + + request = dashboards_service.ListDashboardsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dashboards_service.ListDashboardsResponse() + + client.list_dashboards( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_dashboards_rest_bad_request( + transport: str = "rest", request_type=dashboards_service.ListDashboardsRequest +): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_dashboards(request) + + +def test_list_dashboards_rest_pager(transport: str = "rest"): + client = DashboardsServiceClient( + 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 = ( + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + dashboard.Dashboard(), + dashboard.Dashboard(), + ], + next_page_token="abc", + ), + dashboards_service.ListDashboardsResponse( + dashboards=[], + next_page_token="def", + ), + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + ], + next_page_token="ghi", + ), + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + dashboard.Dashboard(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + dashboards_service.ListDashboardsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1"} + + pager = client.list_dashboards(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dashboard.Dashboard) for i in results) + + pages = list(client.list_dashboards(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", + [ + dashboards_service.GetDashboardRequest, + dict, + ], +) +def test_get_dashboard_rest(request_type): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/dashboards/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 = dashboard.Dashboard( + name="name_value", + display_name="display_name_value", + etag="etag_value", + grid_layout=layouts.GridLayout(columns=769), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dashboard.Dashboard.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_dashboard(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.etag == "etag_value" + + +def test_get_dashboard_rest_required_fields( + request_type=dashboards_service.GetDashboardRequest, +): + transport_class = transports.DashboardsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + 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_dashboard._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_dashboard._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dashboard.Dashboard() + # 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 = dashboard.Dashboard.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_dashboard(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_dashboard_rest_unset_required_fields(): + transport = transports.DashboardsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_dashboard._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_dashboard_rest_interceptors(null_interceptor): + transport = transports.DashboardsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DashboardsServiceRestInterceptor(), + ) + client = DashboardsServiceClient(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.DashboardsServiceRestInterceptor, "post_get_dashboard" + ) as post, mock.patch.object( + transports.DashboardsServiceRestInterceptor, "pre_get_dashboard" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dashboards_service.GetDashboardRequest.pb( + dashboards_service.GetDashboardRequest() + ) + 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 = dashboard.Dashboard.to_json(dashboard.Dashboard()) + + request = dashboards_service.GetDashboardRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dashboard.Dashboard() + + client.get_dashboard( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_dashboard_rest_bad_request( + transport: str = "rest", request_type=dashboards_service.GetDashboardRequest +): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/dashboards/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_dashboard(request) + + +def test_get_dashboard_rest_error(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dashboards_service.DeleteDashboardRequest, + dict, + ], +) +def test_delete_dashboard_rest(request_type): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/dashboards/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_dashboard(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_dashboard_rest_required_fields( + request_type=dashboards_service.DeleteDashboardRequest, +): + transport_class = transports.DashboardsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + 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_dashboard._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_dashboard._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_dashboard(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_dashboard_rest_unset_required_fields(): + transport = transports.DashboardsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_dashboard._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_dashboard_rest_interceptors(null_interceptor): + transport = transports.DashboardsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DashboardsServiceRestInterceptor(), + ) + client = DashboardsServiceClient(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.DashboardsServiceRestInterceptor, "pre_delete_dashboard" + ) as pre: + pre.assert_not_called() + pb_message = dashboards_service.DeleteDashboardRequest.pb( + dashboards_service.DeleteDashboardRequest() + ) + 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() + + request = dashboards_service.DeleteDashboardRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_dashboard( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_dashboard_rest_bad_request( + transport: str = "rest", request_type=dashboards_service.DeleteDashboardRequest +): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/dashboards/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.delete_dashboard(request) + + +def test_delete_dashboard_rest_error(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dashboards_service.UpdateDashboardRequest, + dict, + ], +) +def test_update_dashboard_rest(request_type): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"dashboard": {"name": "projects/sample1/dashboards/sample2"}} + request_init["dashboard"] = { + "name": "projects/sample1/dashboards/sample2", + "display_name": "display_name_value", + "etag": "etag_value", + "grid_layout": { + "columns": 769, + "widgets": [ + { + "title": "title_value", + "xy_chart": { + "data_sets": [ + { + "time_series_query": { + "time_series_filter": { + "filter": "filter_value", + "aggregation": { + "alignment_period": { + "seconds": 751, + "nanos": 543, + }, + "per_series_aligner": 1, + "cross_series_reducer": 1, + "group_by_fields": [ + "group_by_fields_value1", + "group_by_fields_value2", + ], + }, + "secondary_aggregation": {}, + "pick_time_series_filter": { + "ranking_method": 1, + "num_time_series": 1608, + "direction": 1, + }, + "statistical_time_series_filter": { + "ranking_method": 1, + "num_time_series": 1608, + }, + }, + "time_series_filter_ratio": { + "numerator": { + "filter": "filter_value", + "aggregation": {}, + }, + "denominator": {}, + "secondary_aggregation": {}, + "pick_time_series_filter": {}, + "statistical_time_series_filter": {}, + }, + "time_series_query_language": "time_series_query_language_value", + "prometheus_query": "prometheus_query_value", + "unit_override": "unit_override_value", + }, + "plot_type": 1, + "legend_template": "legend_template_value", + "min_alignment_period": {}, + "target_axis": 1, + } + ], + "timeshift_duration": {}, + "thresholds": [ + { + "label": "label_value", + "value": 0.541, + "color": 4, + "direction": 1, + "target_axis": 1, + } + ], + "x_axis": {"label": "label_value", "scale": 1}, + "y_axis": {}, + "y2_axis": {}, + "chart_options": {"mode": 1}, + }, + "scorecard": { + "time_series_query": {}, + "gauge_view": {"lower_bound": 0.1184, "upper_bound": 0.1187}, + "spark_chart_view": { + "spark_chart_type": 1, + "min_alignment_period": {}, + }, + "thresholds": {}, + }, + "text": {"content": "content_value", "format_": 1}, + "blank": {}, + "alert_chart": {"name": "name_value"}, + "time_series_table": { + "data_sets": [ + { + "time_series_query": {}, + "table_template": "table_template_value", + "min_alignment_period": {}, + "table_display_options": { + "shown_columns": [ + "shown_columns_value1", + "shown_columns_value2", + ] + }, + } + ], + "metric_visualization": 1, + "column_settings": [ + {"column": "column_value", "visible": True} + ], + }, + "collapsible_group": {"collapsed": True}, + "logs_panel": { + "filter": "filter_value", + "resource_names": [ + "resource_names_value1", + "resource_names_value2", + ], + }, + } + ], + }, + "mosaic_layout": { + "columns": 769, + "tiles": [ + {"x_pos": 553, "y_pos": 554, "width": 544, "height": 633, "widget": {}} + ], + }, + "row_layout": {"rows": [{"weight": 648, "widgets": {}}]}, + "column_layout": {"columns": [{"weight": 648, "widgets": {}}]}, + "dashboard_filters": [ + { + "label_key": "label_key_value", + "template_variable": "template_variable_value", + "string_value": "string_value_value", + "filter_type": 1, + } + ], + "labels": {}, + } + 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 = dashboard.Dashboard( + name="name_value", + display_name="display_name_value", + etag="etag_value", + grid_layout=layouts.GridLayout(columns=769), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dashboard.Dashboard.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_dashboard(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.etag == "etag_value" + + +def test_update_dashboard_rest_required_fields( + request_type=dashboards_service.UpdateDashboardRequest, +): + transport_class = transports.DashboardsServiceRestTransport + + 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_dashboard._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_dashboard._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dashboard.Dashboard() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dashboard.Dashboard.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_dashboard(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_dashboard_rest_unset_required_fields(): + transport = transports.DashboardsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_dashboard._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly",)) & set(("dashboard",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_dashboard_rest_interceptors(null_interceptor): + transport = transports.DashboardsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DashboardsServiceRestInterceptor(), + ) + client = DashboardsServiceClient(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.DashboardsServiceRestInterceptor, "post_update_dashboard" + ) as post, mock.patch.object( + transports.DashboardsServiceRestInterceptor, "pre_update_dashboard" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dashboards_service.UpdateDashboardRequest.pb( + dashboards_service.UpdateDashboardRequest() + ) + 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 = dashboard.Dashboard.to_json(dashboard.Dashboard()) + + request = dashboards_service.UpdateDashboardRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dashboard.Dashboard() + + client.update_dashboard( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_dashboard_rest_bad_request( + transport: str = "rest", request_type=dashboards_service.UpdateDashboardRequest +): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"dashboard": {"name": "projects/sample1/dashboards/sample2"}} + request_init["dashboard"] = { + "name": "projects/sample1/dashboards/sample2", + "display_name": "display_name_value", + "etag": "etag_value", + "grid_layout": { + "columns": 769, + "widgets": [ + { + "title": "title_value", + "xy_chart": { + "data_sets": [ + { + "time_series_query": { + "time_series_filter": { + "filter": "filter_value", + "aggregation": { + "alignment_period": { + "seconds": 751, + "nanos": 543, + }, + "per_series_aligner": 1, + "cross_series_reducer": 1, + "group_by_fields": [ + "group_by_fields_value1", + "group_by_fields_value2", + ], + }, + "secondary_aggregation": {}, + "pick_time_series_filter": { + "ranking_method": 1, + "num_time_series": 1608, + "direction": 1, + }, + "statistical_time_series_filter": { + "ranking_method": 1, + "num_time_series": 1608, + }, + }, + "time_series_filter_ratio": { + "numerator": { + "filter": "filter_value", + "aggregation": {}, + }, + "denominator": {}, + "secondary_aggregation": {}, + "pick_time_series_filter": {}, + "statistical_time_series_filter": {}, + }, + "time_series_query_language": "time_series_query_language_value", + "prometheus_query": "prometheus_query_value", + "unit_override": "unit_override_value", + }, + "plot_type": 1, + "legend_template": "legend_template_value", + "min_alignment_period": {}, + "target_axis": 1, + } + ], + "timeshift_duration": {}, + "thresholds": [ + { + "label": "label_value", + "value": 0.541, + "color": 4, + "direction": 1, + "target_axis": 1, + } + ], + "x_axis": {"label": "label_value", "scale": 1}, + "y_axis": {}, + "y2_axis": {}, + "chart_options": {"mode": 1}, + }, + "scorecard": { + "time_series_query": {}, + "gauge_view": {"lower_bound": 0.1184, "upper_bound": 0.1187}, + "spark_chart_view": { + "spark_chart_type": 1, + "min_alignment_period": {}, + }, + "thresholds": {}, + }, + "text": {"content": "content_value", "format_": 1}, + "blank": {}, + "alert_chart": {"name": "name_value"}, + "time_series_table": { + "data_sets": [ + { + "time_series_query": {}, + "table_template": "table_template_value", + "min_alignment_period": {}, + "table_display_options": { + "shown_columns": [ + "shown_columns_value1", + "shown_columns_value2", + ] + }, + } + ], + "metric_visualization": 1, + "column_settings": [ + {"column": "column_value", "visible": True} + ], + }, + "collapsible_group": {"collapsed": True}, + "logs_panel": { + "filter": "filter_value", + "resource_names": [ + "resource_names_value1", + "resource_names_value2", + ], + }, + } + ], + }, + "mosaic_layout": { + "columns": 769, + "tiles": [ + {"x_pos": 553, "y_pos": 554, "width": 544, "height": 633, "widget": {}} + ], + }, + "row_layout": {"rows": [{"weight": 648, "widgets": {}}]}, + "column_layout": {"columns": [{"weight": 648, "widgets": {}}]}, + "dashboard_filters": [ + { + "label_key": "label_key_value", + "template_variable": "template_variable_value", + "string_value": "string_value_value", + "filter_type": 1, + } + ], + "labels": {}, + } + 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_dashboard(request) + + +def test_update_dashboard_rest_error(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DashboardsServiceGrpcTransport( @@ -1754,6 +3461,7 @@ def test_transport_get_channel(): [ transports.DashboardsServiceGrpcTransport, transports.DashboardsServiceGrpcAsyncIOTransport, + transports.DashboardsServiceRestTransport, ], ) def test_transport_adc(transport_class): @@ -1768,6 +3476,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1916,6 +3625,7 @@ def test_dashboards_service_transport_auth_adc(transport_class): [ transports.DashboardsServiceGrpcTransport, transports.DashboardsServiceGrpcAsyncIOTransport, + transports.DashboardsServiceRestTransport, ], ) def test_dashboards_service_transport_auth_gdch_credentials(transport_class): @@ -2018,11 +3728,23 @@ def test_dashboards_service_grpc_transport_client_cert_source_for_mtls(transport ) +def test_dashboards_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.DashboardsServiceRestTransport( + 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_dashboards_service_host_no_port(transport_name): @@ -2033,7 +3755,11 @@ def test_dashboards_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("monitoring.googleapis.com:443") + assert client.transport._host == ( + "monitoring.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://monitoring.googleapis.com" + ) @pytest.mark.parametrize( @@ -2041,6 +3767,7 @@ def test_dashboards_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_dashboards_service_host_with_port(transport_name): @@ -2051,7 +3778,45 @@ def test_dashboards_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("monitoring.googleapis.com:8000") + assert client.transport._host == ( + "monitoring.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://monitoring.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_dashboards_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DashboardsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DashboardsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_dashboard._session + session2 = client2.transport.create_dashboard._session + assert session1 != session2 + session1 = client1.transport.list_dashboards._session + session2 = client2.transport.list_dashboards._session + assert session1 != session2 + session1 = client1.transport.get_dashboard._session + session2 = client2.transport.get_dashboard._session + assert session1 != session2 + session1 = client1.transport.delete_dashboard._session + session2 = client2.transport.delete_dashboard._session + assert session1 != session2 + session1 = client1.transport.update_dashboard._session + session2 = client2.transport.update_dashboard._session + assert session1 != session2 def test_dashboards_service_grpc_transport_channel(): @@ -2368,6 +4133,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2385,6 +4151,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: