diff --git a/.librarian/generator-input/client-post-processing/monitoring-dashboards-compatibility.yaml b/.librarian/generator-input/client-post-processing/monitoring-dashboards-compatibility.yaml deleted file mode 100644 index 1eb2435889c0..000000000000 --- a/.librarian/generator-input/client-post-processing/monitoring-dashboards-compatibility.yaml +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright 2026 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. -description: Preserve original index.rst -# Note that we may want to remove the stale directory entirely, at which point -# this file can be deleted too. -url: https://github.com/googleapis/google-cloud-python/issues/11858 -replacements: - - paths: [ - packages/google-cloud-monitoring-dashboards/docs/index.rst - ] - before: | - .. toctree:: - :maxdepth: 2 - - dashboard_v1/services_ - dashboard_v1/types_ - after: | - .. toctree:: - :maxdepth: 2 - - monitoring_dashboard_v1/services_ - monitoring_dashboard_v1/types_ - count: 1 diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard/__init__.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard/__init__.py deleted file mode 100644 index 25002735e4f1..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard/__init__.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import warnings - -from google.monitoring.dashboard_v1.services.dashboards_service.async_client import ( - DashboardsServiceAsyncClient, -) -from google.monitoring.dashboard_v1.services.dashboards_service.client import ( - DashboardsServiceClient, -) -from google.monitoring.dashboard_v1.types.common import ( - Aggregation, - PickTimeSeriesFilter, - StatisticalTimeSeriesFilter, -) -from google.monitoring.dashboard_v1.types.dashboard import Dashboard -from google.monitoring.dashboard_v1.types.dashboards_service import ( - CreateDashboardRequest, - DeleteDashboardRequest, - GetDashboardRequest, - ListDashboardsRequest, - ListDashboardsResponse, - UpdateDashboardRequest, -) -from google.monitoring.dashboard_v1.types.layouts import ( - ColumnLayout, - GridLayout, - RowLayout, -) -from google.monitoring.dashboard_v1.types.metrics import ( - SparkChartType, - Threshold, - TimeSeriesFilter, - TimeSeriesFilterRatio, - TimeSeriesQuery, -) -from google.monitoring.dashboard_v1.types.scorecard import Scorecard -from google.monitoring.dashboard_v1.types.text import Text -from google.monitoring.dashboard_v1.types.widget import Widget -from google.monitoring.dashboard_v1.types.xychart import ChartOptions, XyChart - -__all__ = ( - "Aggregation", - "ChartOptions", - "ColumnLayout", - "CreateDashboardRequest", - "Dashboard", - "DashboardsServiceAsyncClient", - "DashboardsServiceClient", - "DeleteDashboardRequest", - "GetDashboardRequest", - "GridLayout", - "ListDashboardsRequest", - "ListDashboardsResponse", - "PickTimeSeriesFilter", - "RowLayout", - "Scorecard", - "SparkChartType", - "StatisticalTimeSeriesFilter", - "Text", - "Threshold", - "TimeSeriesFilter", - "TimeSeriesFilterRatio", - "TimeSeriesQuery", - "UpdateDashboardRequest", - "Widget", - "XyChart", -) - -import_warning_message = ( - "The client in the `google.monitoring.dashboard` namespace is no longer updated. " - "Please use the client in namespace `google.cloud.monitoring_dashboard` instead. " - "In a future release, importing code from the `google.monitoring.dashboard` namespace " - "may result in a RuntimeError. If you need to continue to use `google.monitoring.dashboard` " - "after this date, please pin to a specific version of 'google-cloud-monitoring-dashboards'. " - "If you have questions, please file an issue: " - "https://github.com/googleapis/python-monitoring-dashboards/issues." -) - -warnings.warn(import_warning_message, ImportWarning) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard/py.typed b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard/py.typed deleted file mode 100644 index a52708e1c180..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-monitoring-dashboard package uses inline types. diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/__init__.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/__init__.py deleted file mode 100644 index 79dff11ec943..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/__init__.py +++ /dev/null @@ -1,81 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import warnings - -from .services.dashboards_service import DashboardsServiceClient -from .types.common import Aggregation, PickTimeSeriesFilter, StatisticalTimeSeriesFilter -from .types.dashboard import Dashboard -from .types.dashboards_service import ( - CreateDashboardRequest, - DeleteDashboardRequest, - GetDashboardRequest, - ListDashboardsRequest, - ListDashboardsResponse, - UpdateDashboardRequest, -) -from .types.layouts import ColumnLayout, GridLayout, RowLayout -from .types.metrics import ( - SparkChartType, - Threshold, - TimeSeriesFilter, - TimeSeriesFilterRatio, - TimeSeriesQuery, -) -from .types.scorecard import Scorecard -from .types.text import Text -from .types.widget import Widget -from .types.xychart import ChartOptions, XyChart - -__all__ = ( - "Aggregation", - "ChartOptions", - "ColumnLayout", - "CreateDashboardRequest", - "Dashboard", - "DeleteDashboardRequest", - "GetDashboardRequest", - "GridLayout", - "ListDashboardsRequest", - "ListDashboardsResponse", - "PickTimeSeriesFilter", - "RowLayout", - "Scorecard", - "SparkChartType", - "StatisticalTimeSeriesFilter", - "Text", - "Threshold", - "TimeSeriesFilter", - "TimeSeriesFilterRatio", - "TimeSeriesQuery", - "UpdateDashboardRequest", - "Widget", - "XyChart", - "DashboardsServiceClient", -) - -import_warning_message = ( - "The client in the `google.monitoring.dashboard` namespace is no longer updated. " - "Please use the client in namespace `google.cloud.monitoring_dashboard` instead. " - "In a future release, importing code from the `google.monitoring.dashboard` namespace " - "may result in a RuntimeError. If you need to continue to use `google.monitoring.dashboard` " - "after this date, please pin to a specific version of 'google-cloud-monitoring-dashboards'. " - "If you have questions, please file an issue: " - "https://github.com/googleapis/python-monitoring-dashboards/issues." -) - -warnings.warn(import_warning_message, ImportWarning) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/gapic_version.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/gapic_version.py deleted file mode 100644 index bdd58a16cd39..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 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. -# -__version__ = "2.22.0" # {x-release-please-version} diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/py.typed b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/py.typed deleted file mode 100644 index a52708e1c180..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-monitoring-dashboard package uses inline types. diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/__init__.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/__init__.py deleted file mode 100644 index 42ffdf2bc43d..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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. -# diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py deleted file mode 100644 index 083fc65fd5c5..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 .async_client import DashboardsServiceAsyncClient -from .client import DashboardsServiceClient - -__all__ = ( - "DashboardsServiceClient", - "DashboardsServiceAsyncClient", -) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py deleted file mode 100644 index f991e886d8c3..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import functools -import re -from collections import OrderedDict -from typing import Dict, Optional, Sequence, Tuple, Type, Union - -from google.api_core import ( - exceptions, # type: ignore - gapic_v1, # type: ignore -) -from google.api_core import retry as retries # type: ignore -from google.api_core.client_options import ClientOptions # type: ignore -from google.auth import credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.monitoring.dashboard_v1 import gapic_version as package_version -from google.monitoring.dashboard_v1.services.dashboards_service import pagers -from google.monitoring.dashboard_v1.types import dashboard, dashboards_service, layouts - -from .client import DashboardsServiceClient -from .transports.base import DashboardsServiceTransport -from .transports.grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - - -class DashboardsServiceAsyncClient: - """Manages Stackdriver dashboards. A dashboard is an arrangement - of data display widgets in a specific layout. - """ - - _client: DashboardsServiceClient - - DEFAULT_ENDPOINT = DashboardsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DashboardsServiceClient.DEFAULT_MTLS_ENDPOINT - - dashboard_path = staticmethod(DashboardsServiceClient.dashboard_path) - - from_service_account_file = DashboardsServiceClient.from_service_account_file - from_service_account_json = from_service_account_file - - get_transport_class = DashboardsServiceClient.get_transport_class - - def __init__( - self, - *, - credentials: Optional[credentials.Credentials] = None, - transport: Union[str, DashboardsServiceTransport, None] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - ) -> None: - """Instantiate the dashboards service client. - - Args: - 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. - transport (Union[str, ~.DashboardsServiceTransport, None]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[ClientOptions]): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - - self._client = DashboardsServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - ) - - async def create_dashboard( - self, - request: Optional[dashboards_service.CreateDashboardRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Creates a new custom dashboard. - - This method requires the ``monitoring.dashboards.create`` - permission on the specified project. For more information, see - `Google Cloud IAM `__. - - Args: - request (:class:`~.dashboards_service.CreateDashboardRequest`): - The request object. The `CreateDashboard` request. - - retry (OptionalRetry): Designation of what errors, if any, - should be retried. - timeout (Optional[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. - - """ - # Create or coerce a protobuf request object. - - request = dashboards_service.CreateDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_dashboard, - default_timeout=30.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_dashboards( - self, - request: Optional[dashboards_service.ListDashboardsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDashboardsAsyncPager: - r"""Lists the existing dashboards. - - This method requires the ``monitoring.dashboards.list`` - permission on the specified project. For more information, see - `Google Cloud IAM `__. - - Args: - request (:class:`~.dashboards_service.ListDashboardsRequest`): - The request object. The `ListDashboards` request. - - retry (OptionalRetry): Designation of what errors, if any, - should be retried. - timeout (Optional[float]): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListDashboardsAsyncPager: - The ``ListDashboards`` request. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - - request = dashboards_service.ListDashboardsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_dashboards, - default_timeout=None, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDashboardsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_dashboard( - self, - request: Optional[dashboards_service.GetDashboardRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Fetches a specific dashboard. - - This method requires the ``monitoring.dashboards.get`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Args: - request (:class:`~.dashboards_service.GetDashboardRequest`): - The request object. The `GetDashboard` request. - - retry (OptionalRetry): Designation of what errors, if any, - should be retried. - timeout (Optional[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. - - """ - # Create or coerce a protobuf request object. - - request = dashboards_service.GetDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_dashboard, - default_timeout=None, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_dashboard( - self, - request: Optional[dashboards_service.DeleteDashboardRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing custom dashboard. - - This method requires the ``monitoring.dashboards.delete`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Args: - request (:class:`~.dashboards_service.DeleteDashboardRequest`): - The request object. The `DeleteDashboard` request. - - retry (OptionalRetry): Designation of what errors, if any, - should be retried. - timeout (Optional[float]): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - - request = dashboards_service.DeleteDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_dashboard, - default_timeout=30.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_dashboard( - self, - request: Optional[dashboards_service.UpdateDashboardRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Replaces an existing custom dashboard with a new definition. - - This method requires the ``monitoring.dashboards.update`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Args: - request (:class:`~.dashboards_service.UpdateDashboardRequest`): - The request object. The `UpdateDashboard` request. - - retry (OptionalRetry): Designation of what errors, if any, - should be retried. - timeout (Optional[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. - - """ - # Create or coerce a protobuf request object. - - request = dashboards_service.UpdateDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_dashboard, - default_timeout=30.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("dashboard.name", request.dashboard.name),) - ), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - -_client_info = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - - -__all__ = ("DashboardsServiceAsyncClient",) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/client.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/client.py deleted file mode 100644 index 0452d5ef98af..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/client.py +++ /dev/null @@ -1,538 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os -import re -from collections import OrderedDict -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union - -import google.api_core.client_options as client_options_lib # type: ignore -from google.api_core import ( - exceptions, # type: ignore - gapic_v1, # type: ignore -) -from google.api_core import retry as retries -from google.auth import credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.monitoring.dashboard_v1 import gapic_version as package_version -from google.monitoring.dashboard_v1.services.dashboards_service import pagers -from google.monitoring.dashboard_v1.types import dashboard, dashboards_service, layouts - -from .transports.base import DashboardsServiceTransport -from .transports.grpc import DashboardsServiceGrpcTransport -from .transports.grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -class DashboardsServiceClientMeta(type): - """Metaclass for the DashboardsService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - - _transport_registry = OrderedDict() # type: Dict[str, Type[DashboardsServiceTransport]] - _transport_registry["grpc"] = DashboardsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DashboardsServiceGrpcAsyncIOTransport - - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[DashboardsServiceTransport]: - """Return an appropriate transport class. - - Args: - label (Optional[str]): The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DashboardsServiceClient(metaclass=DashboardsServiceClientMeta): - """Manages Stackdriver dashboards. A dashboard is an arrangement - of data display widgets in a specific layout. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "monitoring.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - {@api.name}: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @staticmethod - def dashboard_path( - project: str, - dashboard: str, - ) -> str: - """Return a fully-qualified dashboard string.""" - return "projects/{project}/dashboards/{dashboard}".format( - project=project, - dashboard=dashboard, - ) - - @staticmethod - def parse_dashboard_path(path: str) -> Dict[str, str]: - """Parse a dashboard path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/dashboards/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__( - self, - *, - credentials: Optional[credentials.Credentials] = None, - transport: Union[str, DashboardsServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - ) -> None: - """Instantiate the dashboards service client. - - Args: - 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. - transport (Union[str, ~.DashboardsServiceTransport, None]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[google.api_core.client_options.ClientOptions]): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.ClientOptions.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") - if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT - ) - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DashboardsServiceTransport): - # transport is a DashboardsServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=client_options.api_endpoint, - scopes=client_options.scopes, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, - quota_project_id=client_options.quota_project_id, - ) - - def create_dashboard( - self, - request: Optional[dashboards_service.CreateDashboardRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Creates a new custom dashboard. - - This method requires the ``monitoring.dashboards.create`` - permission on the specified project. For more information, see - `Google Cloud IAM `__. - - Args: - request (:class:`~.dashboards_service.CreateDashboardRequest`): - The request object. The `CreateDashboard` request. - - retry (OptionalRetry): Designation of what errors, if any, - should be retried. - timeout (Optional[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. - - """ - # Create or coerce a protobuf request object. - - request = dashboards_service.CreateDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_dashboard] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_dashboards( - self, - request: Optional[dashboards_service.ListDashboardsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDashboardsPager: - r"""Lists the existing dashboards. - - This method requires the ``monitoring.dashboards.list`` - permission on the specified project. For more information, see - `Google Cloud IAM `__. - - Args: - request (:class:`~.dashboards_service.ListDashboardsRequest`): - The request object. The `ListDashboards` request. - - retry (OptionalRetry): Designation of what errors, if any, - should be retried. - timeout (Optional[float]): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListDashboardsPager: - The ``ListDashboards`` request. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - - request = dashboards_service.ListDashboardsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_dashboards] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDashboardsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_dashboard( - self, - request: Optional[dashboards_service.GetDashboardRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Fetches a specific dashboard. - - This method requires the ``monitoring.dashboards.get`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Args: - request (:class:`~.dashboards_service.GetDashboardRequest`): - The request object. The `GetDashboard` request. - - retry (OptionalRetry): Designation of what errors, if any, - should be retried. - timeout (Optional[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. - - """ - # Create or coerce a protobuf request object. - - request = dashboards_service.GetDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_dashboard] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_dashboard( - self, - request: Optional[dashboards_service.DeleteDashboardRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing custom dashboard. - - This method requires the ``monitoring.dashboards.delete`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Args: - request (:class:`~.dashboards_service.DeleteDashboardRequest`): - The request object. The `DeleteDashboard` request. - - retry (OptionalRetry): Designation of what errors, if any, - should be retried. - timeout (Optional[float]): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - - request = dashboards_service.DeleteDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_dashboard] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_dashboard( - self, - request: Optional[dashboards_service.UpdateDashboardRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Replaces an existing custom dashboard with a new definition. - - This method requires the ``monitoring.dashboards.update`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Args: - request (:class:`~.dashboards_service.UpdateDashboardRequest`): - The request object. The `UpdateDashboard` request. - - retry (OptionalRetry): Designation of what errors, if any, - should be retried. - timeout (Optional[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. - - """ - # Create or coerce a protobuf request object. - - request = dashboards_service.UpdateDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_dashboard] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("dashboard.name", request.dashboard.name),) - ), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - -_client_info = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - - -__all__ = ("DashboardsServiceClient",) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py deleted file mode 100644 index 674e9a9a46b3..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py +++ /dev/null @@ -1,148 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple - -from google.monitoring.dashboard_v1.types import dashboard, dashboards_service - - -class ListDashboardsPager: - """A pager for iterating through ``list_dashboards`` requests. - - This class thinly wraps an initial - :class:`~.dashboards_service.ListDashboardsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``dashboards`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDashboards`` requests and continue to iterate - through the ``dashboards`` field on the - corresponding responses. - - All the usual :class:`~.dashboards_service.ListDashboardsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., dashboards_service.ListDashboardsResponse], - request: dashboards_service.ListDashboardsRequest, - response: dashboards_service.ListDashboardsResponse, - *, - metadata: Sequence[Tuple[str, str]] = (), - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.dashboards_service.ListDashboardsRequest`): - The initial request object. - response (:class:`~.dashboards_service.ListDashboardsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = dashboards_service.ListDashboardsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[dashboards_service.ListDashboardsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[dashboard.Dashboard]: - for page in self.pages: - yield from page.dashboards - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListDashboardsAsyncPager: - """A pager for iterating through ``list_dashboards`` requests. - - This class thinly wraps an initial - :class:`~.dashboards_service.ListDashboardsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``dashboards`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDashboards`` requests and continue to iterate - through the ``dashboards`` field on the - corresponding responses. - - All the usual :class:`~.dashboards_service.ListDashboardsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[dashboards_service.ListDashboardsResponse]], - request: dashboards_service.ListDashboardsRequest, - response: dashboards_service.ListDashboardsResponse, - *, - metadata: Sequence[Tuple[str, str]] = (), - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.dashboards_service.ListDashboardsRequest`): - The initial request object. - response (:class:`~.dashboards_service.ListDashboardsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = dashboards_service.ListDashboardsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[dashboards_service.ListDashboardsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[dashboard.Dashboard]: - async def async_generator(): - async for page in self.pages: - for response in page.dashboards: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py deleted file mode 100644 index 8d10f0449262..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 collections import OrderedDict -from typing import Dict, Type - -from .base import DashboardsServiceTransport -from .grpc import DashboardsServiceGrpcTransport -from .grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DashboardsServiceTransport]] -_transport_registry["grpc"] = DashboardsServiceGrpcTransport -_transport_registry["grpc_asyncio"] = DashboardsServiceGrpcAsyncIOTransport - - -__all__ = ( - "DashboardsServiceTransport", - "DashboardsServiceGrpcTransport", - "DashboardsServiceGrpcAsyncIOTransport", -) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py deleted file mode 100644 index a40487895e60..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import abc -import typing - -from google.api_core import ( - exceptions, # type: ignore - gapic_v1, # type: ignore -) -from google.auth import credentials # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - -from google import auth -from google.monitoring.dashboard_v1 import gapic_version as package_version -from google.monitoring.dashboard_v1.types import dashboard, dashboards_service - -_client_info = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - - -class DashboardsServiceTransport(abc.ABC): - """Abstract transport class for DashboardsService.""" - - AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ) - - def __init__( - self, - *, - host: str = "monitoring.googleapis.com", - credentials: typing.Optional[credentials.Credentials] = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, - **kwargs, - ) -> 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 mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) - - if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id - ) - - # Save the credentials. - self._credentials = credentials - - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages() - - def _prep_wrapped_messages(self): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_dashboard: gapic_v1.method.wrap_method( - self.create_dashboard, - default_timeout=30.0, - client_info=_client_info, - ), - self.list_dashboards: gapic_v1.method.wrap_method( - self.list_dashboards, - default_timeout=None, - client_info=_client_info, - ), - self.get_dashboard: gapic_v1.method.wrap_method( - self.get_dashboard, - default_timeout=None, - client_info=_client_info, - ), - self.delete_dashboard: gapic_v1.method.wrap_method( - self.delete_dashboard, - default_timeout=30.0, - client_info=_client_info, - ), - self.update_dashboard: gapic_v1.method.wrap_method( - self.update_dashboard, - default_timeout=30.0, - client_info=_client_info, - ), - } - - @property - def create_dashboard( - self, - ) -> typing.Callable[ - [dashboards_service.CreateDashboardRequest], - typing.Union[dashboard.Dashboard, typing.Awaitable[dashboard.Dashboard]], - ]: - raise NotImplementedError() - - @property - def list_dashboards( - self, - ) -> typing.Callable[ - [dashboards_service.ListDashboardsRequest], - typing.Union[ - dashboards_service.ListDashboardsResponse, - typing.Awaitable[dashboards_service.ListDashboardsResponse], - ], - ]: - raise NotImplementedError() - - @property - def get_dashboard( - self, - ) -> typing.Callable[ - [dashboards_service.GetDashboardRequest], - typing.Union[dashboard.Dashboard, typing.Awaitable[dashboard.Dashboard]], - ]: - raise NotImplementedError() - - @property - def delete_dashboard( - self, - ) -> typing.Callable[ - [dashboards_service.DeleteDashboardRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], - ]: - raise NotImplementedError() - - @property - def update_dashboard( - self, - ) -> typing.Callable[ - [dashboards_service.UpdateDashboardRequest], - typing.Union[dashboard.Dashboard, typing.Awaitable[dashboard.Dashboard]], - ]: - raise NotImplementedError() - - -__all__ = ("DashboardsServiceTransport",) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py deleted file mode 100644 index 0345fcb0875a..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py +++ /dev/null @@ -1,361 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Callable, Dict, Optional, Sequence, Tuple - -import grpc # type: ignore -from google.api_core import grpc_helpers # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - -from google import auth # type: ignore -from google.monitoring.dashboard_v1.types import dashboard, dashboards_service - -from .base import DashboardsServiceTransport - - -class DashboardsServiceGrpcTransport(DashboardsServiceTransport): - """gRPC 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 protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _stubs: Dict[str, Callable] - - def __init__( - self, - *, - host: str = "monitoring.googleapis.com", - credentials: Optional[credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: 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. - This argument is ignored if ``channel`` is provided. - 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. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. - credentials = None - - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - @classmethod - def create_channel( - cls, - host: str = "monitoring.googleapis.com", - credentials: Optional[credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this 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 mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - scopes = scopes or cls.AUTH_SCOPES - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - **kwargs, - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, - credentials=self._credentials, - ) - - # Return the channel from cache. - return self._grpc_channel - - @property - def create_dashboard( - self, - ) -> Callable[[dashboards_service.CreateDashboardRequest], dashboard.Dashboard]: - r"""Return a callable for the create dashboard method over gRPC. - - Creates a new custom dashboard. - - This method requires the ``monitoring.dashboards.create`` - permission on the specified project. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.CreateDashboardRequest], - ~.Dashboard]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "create_dashboard" not in self._stubs: - self._stubs["create_dashboard"] = self.grpc_channel.unary_unary( - "/google.monitoring.dashboard.v1.DashboardsService/CreateDashboard", - request_serializer=dashboards_service.CreateDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs["create_dashboard"] - - @property - def list_dashboards( - self, - ) -> Callable[ - [dashboards_service.ListDashboardsRequest], - dashboards_service.ListDashboardsResponse, - ]: - r"""Return a callable for the list dashboards method over gRPC. - - Lists the existing dashboards. - - This method requires the ``monitoring.dashboards.list`` - permission on the specified project. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.ListDashboardsRequest], - ~.ListDashboardsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_dashboards" not in self._stubs: - self._stubs["list_dashboards"] = self.grpc_channel.unary_unary( - "/google.monitoring.dashboard.v1.DashboardsService/ListDashboards", - request_serializer=dashboards_service.ListDashboardsRequest.serialize, - response_deserializer=dashboards_service.ListDashboardsResponse.deserialize, - ) - return self._stubs["list_dashboards"] - - @property - def get_dashboard( - self, - ) -> Callable[[dashboards_service.GetDashboardRequest], dashboard.Dashboard]: - r"""Return a callable for the get dashboard method over gRPC. - - Fetches a specific dashboard. - - This method requires the ``monitoring.dashboards.get`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.GetDashboardRequest], - ~.Dashboard]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_dashboard" not in self._stubs: - self._stubs["get_dashboard"] = self.grpc_channel.unary_unary( - "/google.monitoring.dashboard.v1.DashboardsService/GetDashboard", - request_serializer=dashboards_service.GetDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs["get_dashboard"] - - @property - def delete_dashboard( - self, - ) -> Callable[[dashboards_service.DeleteDashboardRequest], empty.Empty]: - r"""Return a callable for the delete dashboard method over gRPC. - - Deletes an existing custom dashboard. - - This method requires the ``monitoring.dashboards.delete`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.DeleteDashboardRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_dashboard" not in self._stubs: - self._stubs["delete_dashboard"] = self.grpc_channel.unary_unary( - "/google.monitoring.dashboard.v1.DashboardsService/DeleteDashboard", - request_serializer=dashboards_service.DeleteDashboardRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs["delete_dashboard"] - - @property - def update_dashboard( - self, - ) -> Callable[[dashboards_service.UpdateDashboardRequest], dashboard.Dashboard]: - r"""Return a callable for the update dashboard method over gRPC. - - Replaces an existing custom dashboard with a new definition. - - This method requires the ``monitoring.dashboards.update`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.UpdateDashboardRequest], - ~.Dashboard]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "update_dashboard" not in self._stubs: - self._stubs["update_dashboard"] = self.grpc_channel.unary_unary( - "/google.monitoring.dashboard.v1.DashboardsService/UpdateDashboard", - request_serializer=dashboards_service.UpdateDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs["update_dashboard"] - - -__all__ = ("DashboardsServiceGrpcTransport",) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py deleted file mode 100644 index a2a1cab3ee46..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,361 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple - -import grpc # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from grpc.experimental import aio # type: ignore - -from google.monitoring.dashboard_v1.types import dashboard, dashboards_service - -from .base import DashboardsServiceTransport -from .grpc import DashboardsServiceGrpcTransport - - -class DashboardsServiceGrpcAsyncIOTransport(DashboardsServiceTransport): - """gRPC AsyncIO 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 protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel( - cls, - host: str = "monitoring.googleapis.com", - credentials: Optional[credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this 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 optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - scopes = scopes or cls.AUTH_SCOPES - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - **kwargs, - ) - - def __init__( - self, - *, - host: str = "monitoring.googleapis.com", - credentials: Optional[credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id=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. - This argument is ignored if ``channel`` is provided. - 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 optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. - credentials = None - - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - self._stubs = {} - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, - credentials=self._credentials, - ) - - # Return the channel from cache. - return self._grpc_channel - - @property - def create_dashboard( - self, - ) -> Callable[ - [dashboards_service.CreateDashboardRequest], Awaitable[dashboard.Dashboard] - ]: - r"""Return a callable for the create dashboard method over gRPC. - - Creates a new custom dashboard. - - This method requires the ``monitoring.dashboards.create`` - permission on the specified project. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.CreateDashboardRequest], - Awaitable[~.Dashboard]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "create_dashboard" not in self._stubs: - self._stubs["create_dashboard"] = self.grpc_channel.unary_unary( - "/google.monitoring.dashboard.v1.DashboardsService/CreateDashboard", - request_serializer=dashboards_service.CreateDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs["create_dashboard"] - - @property - def list_dashboards( - self, - ) -> Callable[ - [dashboards_service.ListDashboardsRequest], - Awaitable[dashboards_service.ListDashboardsResponse], - ]: - r"""Return a callable for the list dashboards method over gRPC. - - Lists the existing dashboards. - - This method requires the ``monitoring.dashboards.list`` - permission on the specified project. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.ListDashboardsRequest], - Awaitable[~.ListDashboardsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_dashboards" not in self._stubs: - self._stubs["list_dashboards"] = self.grpc_channel.unary_unary( - "/google.monitoring.dashboard.v1.DashboardsService/ListDashboards", - request_serializer=dashboards_service.ListDashboardsRequest.serialize, - response_deserializer=dashboards_service.ListDashboardsResponse.deserialize, - ) - return self._stubs["list_dashboards"] - - @property - def get_dashboard( - self, - ) -> Callable[ - [dashboards_service.GetDashboardRequest], Awaitable[dashboard.Dashboard] - ]: - r"""Return a callable for the get dashboard method over gRPC. - - Fetches a specific dashboard. - - This method requires the ``monitoring.dashboards.get`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.GetDashboardRequest], - Awaitable[~.Dashboard]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_dashboard" not in self._stubs: - self._stubs["get_dashboard"] = self.grpc_channel.unary_unary( - "/google.monitoring.dashboard.v1.DashboardsService/GetDashboard", - request_serializer=dashboards_service.GetDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs["get_dashboard"] - - @property - def delete_dashboard( - self, - ) -> Callable[[dashboards_service.DeleteDashboardRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the delete dashboard method over gRPC. - - Deletes an existing custom dashboard. - - This method requires the ``monitoring.dashboards.delete`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.DeleteDashboardRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_dashboard" not in self._stubs: - self._stubs["delete_dashboard"] = self.grpc_channel.unary_unary( - "/google.monitoring.dashboard.v1.DashboardsService/DeleteDashboard", - request_serializer=dashboards_service.DeleteDashboardRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs["delete_dashboard"] - - @property - def update_dashboard( - self, - ) -> Callable[ - [dashboards_service.UpdateDashboardRequest], Awaitable[dashboard.Dashboard] - ]: - r"""Return a callable for the update dashboard method over gRPC. - - Replaces an existing custom dashboard with a new definition. - - This method requires the ``monitoring.dashboards.update`` - permission on the specified dashboard. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.UpdateDashboardRequest], - Awaitable[~.Dashboard]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "update_dashboard" not in self._stubs: - self._stubs["update_dashboard"] = self.grpc_channel.unary_unary( - "/google.monitoring.dashboard.v1.DashboardsService/UpdateDashboard", - request_serializer=dashboards_service.UpdateDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs["update_dashboard"] - - -__all__ = ("DashboardsServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/__init__.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/__init__.py deleted file mode 100644 index 346f6a9ece43..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/__init__.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 .common import Aggregation, PickTimeSeriesFilter, StatisticalTimeSeriesFilter -from .dashboard import Dashboard -from .dashboards_service import ( - CreateDashboardRequest, - DeleteDashboardRequest, - GetDashboardRequest, - ListDashboardsRequest, - ListDashboardsResponse, - UpdateDashboardRequest, -) -from .layouts import ColumnLayout, GridLayout, RowLayout -from .metrics import Threshold, TimeSeriesFilter, TimeSeriesFilterRatio, TimeSeriesQuery -from .scorecard import Scorecard -from .text import Text -from .widget import Widget -from .xychart import ChartOptions, XyChart - -__all__ = ( - "Aggregation", - "PickTimeSeriesFilter", - "StatisticalTimeSeriesFilter", - "TimeSeriesQuery", - "TimeSeriesFilter", - "TimeSeriesFilterRatio", - "Threshold", - "Scorecard", - "Text", - "XyChart", - "ChartOptions", - "Widget", - "GridLayout", - "RowLayout", - "ColumnLayout", - "Dashboard", - "CreateDashboardRequest", - "ListDashboardsRequest", - "ListDashboardsResponse", - "GetDashboardRequest", - "DeleteDashboardRequest", - "UpdateDashboardRequest", -) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/common.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/common.py deleted file mode 100644 index 1ec5aec27126..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/common.py +++ /dev/null @@ -1,300 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore -from google.protobuf import duration_pb2 as duration # type: ignore - -__protobuf__ = proto.module( - package="google.monitoring.dashboard.v1", - manifest={ - "Aggregation", - "PickTimeSeriesFilter", - "StatisticalTimeSeriesFilter", - }, -) - - -class Aggregation(proto.Message): - r"""Describes how to combine multiple time series to provide a different - view of the data. Aggregation of time series is done in two steps. - First, each time series in the set is *aligned* to the same time - interval boundaries, then the set of time series is optionally - *reduced* in number. - - Alignment consists of applying the ``per_series_aligner`` operation - to each time series after its data has been divided into regular - ``alignment_period`` time intervals. This process takes *all* of the - data points in an alignment period, applies a mathematical - transformation such as averaging, minimum, maximum, delta, etc., and - converts them into a single data point per period. - - Reduction is when the aligned and transformed time series can - optionally be combined, reducing the number of time series through - similar mathematical transformations. Reduction involves applying a - ``cross_series_reducer`` to all the time series, optionally sorting - the time series into subsets with ``group_by_fields``, and applying - the reducer to each subset. - - The raw time series data can contain a huge amount of information - from multiple sources. Alignment and reduction transforms this mass - of data into a more manageable and representative collection of - data, for example "the 95% latency across the average of all tasks - in a cluster". This representative data can be more easily graphed - and comprehended, and the individual time series data is still - available for later drilldown. For more details, see `Filtering and - aggregation `__. - - Attributes: - alignment_period (~.duration.Duration): - The ``alignment_period`` specifies a time interval, in - seconds, that is used to divide the data in all the [time - series][google.monitoring.v3.TimeSeries] into consistent - blocks of time. This will be done before the per-series - aligner can be applied to the data. - - The value must be at least 60 seconds. If a per-series - aligner other than ``ALIGN_NONE`` is specified, this field - is required or an error is returned. If no per-series - aligner is specified, or the aligner ``ALIGN_NONE`` is - specified, then this field is ignored. - per_series_aligner (~.common.Aggregation.Aligner): - An ``Aligner`` describes how to bring the data points in a - single time series into temporal alignment. Except for - ``ALIGN_NONE``, all alignments cause all the data points in - an ``alignment_period`` to be mathematically grouped - together, resulting in a single data point for each - ``alignment_period`` with end timestamp at the end of the - period. - - Not all alignment operations may be applied to all time - series. The valid choices depend on the ``metric_kind`` and - ``value_type`` of the original time series. Alignment can - change the ``metric_kind`` or the ``value_type`` of the time - series. - - Time series data must be aligned in order to perform - cross-time series reduction. If ``cross_series_reducer`` is - specified, then ``per_series_aligner`` must be specified and - not equal to ``ALIGN_NONE`` and ``alignment_period`` must be - specified; otherwise, an error is returned. - cross_series_reducer (~.common.Aggregation.Reducer): - The reduction operation to be used to combine time series - into a single time series, where the value of each data - point in the resulting series is a function of all the - already aligned values in the input time series. - - Not all reducer operations can be applied to all time - series. The valid choices depend on the ``metric_kind`` and - the ``value_type`` of the original time series. Reduction - can yield a time series with a different ``metric_kind`` or - ``value_type`` than the input time series. - - Time series data must first be aligned (see - ``per_series_aligner``) in order to perform cross-time - series reduction. If ``cross_series_reducer`` is specified, - then ``per_series_aligner`` must be specified, and must not - be ``ALIGN_NONE``. An ``alignment_period`` must also be - specified; otherwise, an error is returned. - group_by_fields (Sequence[str]): - The set of fields to preserve when ``cross_series_reducer`` - is specified. The ``group_by_fields`` determine how the time - series are partitioned into subsets prior to applying the - aggregation operation. Each subset contains time series that - have the same value for each of the grouping fields. Each - individual time series is a member of exactly one subset. - The ``cross_series_reducer`` is applied to each subset of - time series. It is not possible to reduce across different - resource types, so this field implicitly contains - ``resource.type``. Fields not specified in - ``group_by_fields`` are aggregated away. If - ``group_by_fields`` is not specified and all the time series - have the same resource type, then the time series are - aggregated into a single output time series. If - ``cross_series_reducer`` is not defined, this field is - ignored. - """ - - class Aligner(proto.Enum): - r"""The ``Aligner`` specifies the operation that will be applied to the - data points in each alignment period in a time series. Except for - ``ALIGN_NONE``, which specifies that no operation be applied, each - alignment operation replaces the set of data values in each - alignment period with a single value: the result of applying the - operation to the data values. An aligned time series has a single - data value at the end of each ``alignment_period``. - - An alignment operation can change the data type of the values, too. - For example, if you apply a counting operation to boolean values, - the data ``value_type`` in the original time series is ``BOOLEAN``, - but the ``value_type`` in the aligned result is ``INT64``. - """ - - ALIGN_NONE = 0 - ALIGN_DELTA = 1 - ALIGN_RATE = 2 - ALIGN_INTERPOLATE = 3 - ALIGN_NEXT_OLDER = 4 - ALIGN_MIN = 10 - ALIGN_MAX = 11 - ALIGN_MEAN = 12 - ALIGN_COUNT = 13 - ALIGN_SUM = 14 - ALIGN_STDDEV = 15 - ALIGN_COUNT_TRUE = 16 - ALIGN_COUNT_FALSE = 24 - ALIGN_FRACTION_TRUE = 17 - ALIGN_PERCENTILE_99 = 18 - ALIGN_PERCENTILE_95 = 19 - ALIGN_PERCENTILE_50 = 20 - ALIGN_PERCENTILE_05 = 21 - ALIGN_PERCENT_CHANGE = 23 - - class Reducer(proto.Enum): - r"""A Reducer operation describes how to aggregate data points - from multiple time series into a single time series, where the - value of each data point in the resulting series is a function - of all the already aligned values in the input time series. - """ - - REDUCE_NONE = 0 - REDUCE_MEAN = 1 - REDUCE_MIN = 2 - REDUCE_MAX = 3 - REDUCE_SUM = 4 - REDUCE_STDDEV = 5 - REDUCE_COUNT = 6 - REDUCE_COUNT_TRUE = 7 - REDUCE_COUNT_FALSE = 15 - REDUCE_FRACTION_TRUE = 8 - REDUCE_PERCENTILE_99 = 9 - REDUCE_PERCENTILE_95 = 10 - REDUCE_PERCENTILE_50 = 11 - REDUCE_PERCENTILE_05 = 12 - - alignment_period = proto.Field( - proto.MESSAGE, - number=1, - message=duration.Duration, - ) - - per_series_aligner = proto.Field( - proto.ENUM, - number=2, - enum=Aligner, - ) - - cross_series_reducer = proto.Field( - proto.ENUM, - number=4, - enum=Reducer, - ) - - group_by_fields = proto.RepeatedField(proto.STRING, number=5) - - -class PickTimeSeriesFilter(proto.Message): - r"""Describes a ranking-based time series filter. Each input time series - is ranked with an aligner. The filter will allow up to - ``num_time_series`` time series to pass through it, selecting them - based on the relative ranking. - - For example, if ``ranking_method`` is - ``METHOD_MEAN``,\ ``direction`` is ``BOTTOM``, and - ``num_time_series`` is 3, then the 3 times series with the lowest - mean values will pass through the filter. - - Attributes: - ranking_method (~.common.PickTimeSeriesFilter.Method): - ``ranking_method`` is applied to each time series - independently to produce the value which will be used to - compare the time series to other time series. - num_time_series (int): - How many time series to allow to pass through - the filter. - direction (~.common.PickTimeSeriesFilter.Direction): - How to use the ranking to select time series - that pass through the filter. - """ - - class Method(proto.Enum): - r"""The value reducers that can be applied to a - ``PickTimeSeriesFilter``. - """ - - METHOD_UNSPECIFIED = 0 - METHOD_MEAN = 1 - METHOD_MAX = 2 - METHOD_MIN = 3 - METHOD_SUM = 4 - METHOD_LATEST = 5 - - class Direction(proto.Enum): - r"""Describes the ranking directions.""" - - DIRECTION_UNSPECIFIED = 0 - TOP = 1 - BOTTOM = 2 - - ranking_method = proto.Field( - proto.ENUM, - number=1, - enum=Method, - ) - - num_time_series = proto.Field(proto.INT32, number=2) - - direction = proto.Field( - proto.ENUM, - number=3, - enum=Direction, - ) - - -class StatisticalTimeSeriesFilter(proto.Message): - r"""A filter that ranks streams based on their statistical - relation to other streams in a request. - Note: This field is deprecated and completely ignored by the - API. - - Attributes: - ranking_method (~.common.StatisticalTimeSeriesFilter.Method): - ``rankingMethod`` is applied to a set of time series, and - then the produced value for each individual time series is - used to compare a given time series to others. These are - methods that cannot be applied stream-by-stream, but rather - require the full context of a request to evaluate time - series. - num_time_series (int): - How many time series to output. - """ - - class Method(proto.Enum): - r"""The filter methods that can be applied to a stream.""" - - METHOD_UNSPECIFIED = 0 - METHOD_CLUSTER_OUTLIER = 1 - - ranking_method = proto.Field( - proto.ENUM, - number=1, - enum=Method, - ) - - num_time_series = proto.Field(proto.INT32, number=2) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/dashboard.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/dashboard.py deleted file mode 100644 index 7d3b2b0e2493..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/dashboard.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import layouts - -__protobuf__ = proto.module( - package="google.monitoring.dashboard.v1", - manifest={ - "Dashboard", - }, -) - - -class Dashboard(proto.Message): - r"""A Google Stackdriver dashboard. Dashboards define the content - and layout of pages in the Stackdriver web application. - - Attributes: - name (str): - Immutable. The resource name of the - dashboard. - display_name (str): - Required. The mutable, human-readable name. - etag (str): - ``etag`` is used for optimistic concurrency control as a way - to help prevent simultaneous updates of a policy from - overwriting each other. An ``etag`` is returned in the - response to ``GetDashboard``, and users are expected to put - that etag in the request to ``UpdateDashboard`` to ensure - that their change will be applied to the same version of the - Dashboard configuration. The field should not be passed - during dashboard creation. - grid_layout (~.layouts.GridLayout): - Content is arranged with a basic layout that - re-flows a simple list of informational elements - like widgets or tiles. - row_layout (~.layouts.RowLayout): - The content is divided into equally spaced - rows and the widgets are arranged horizontally. - column_layout (~.layouts.ColumnLayout): - The content is divided into equally spaced - columns and the widgets are arranged vertically. - """ - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - etag = proto.Field(proto.STRING, number=4) - - grid_layout = proto.Field( - proto.MESSAGE, - number=5, - oneof="layout", - message=layouts.GridLayout, - ) - - row_layout = proto.Field( - proto.MESSAGE, - number=8, - oneof="layout", - message=layouts.RowLayout, - ) - - column_layout = proto.Field( - proto.MESSAGE, - number=9, - oneof="layout", - message=layouts.ColumnLayout, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/dashboards_service.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/dashboards_service.py deleted file mode 100644 index 4f45417ed7aa..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/dashboards_service.py +++ /dev/null @@ -1,165 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import dashboard as gmd_dashboard - -__protobuf__ = proto.module( - package="google.monitoring.dashboard.v1", - manifest={ - "CreateDashboardRequest", - "ListDashboardsRequest", - "ListDashboardsResponse", - "GetDashboardRequest", - "DeleteDashboardRequest", - "UpdateDashboardRequest", - }, -) - - -class CreateDashboardRequest(proto.Message): - r"""The ``CreateDashboard`` request. - - Attributes: - parent (str): - Required. The project on which to execute the request. The - format is: - - :: - - projects/[PROJECT_ID_OR_NUMBER] - - The ``[PROJECT_ID_OR_NUMBER]`` must match the dashboard - resource name. - dashboard (~.gmd_dashboard.Dashboard): - Required. The initial dashboard - specification. - """ - - parent = proto.Field(proto.STRING, number=1) - - dashboard = proto.Field( - proto.MESSAGE, - number=2, - message=gmd_dashboard.Dashboard, - ) - - -class ListDashboardsRequest(proto.Message): - r"""The ``ListDashboards`` request. - - Attributes: - parent (str): - Required. The scope of the dashboards to list. The format - is: - - :: - - projects/[PROJECT_ID_OR_NUMBER] - page_size (int): - A positive number that is the maximum number - of results to return. If unspecified, a default - of 1000 is used. - page_token (str): - If this field is not empty then it must contain the - ``nextPageToken`` value returned by a previous call to this - method. Using this field causes the method to return - additional results from the previous method call. - """ - - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - -class ListDashboardsResponse(proto.Message): - r"""The ``ListDashboards`` request. - - Attributes: - dashboards (Sequence[~.gmd_dashboard.Dashboard]): - The list of requested dashboards. - next_page_token (str): - If there are more results than have been returned, then this - field is set to a non-empty value. To see the additional - results, use that value as ``page_token`` in the next call - to this method. - """ - - @property - def raw_page(self): - return self - - dashboards = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gmd_dashboard.Dashboard, - ) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class GetDashboardRequest(proto.Message): - r"""The ``GetDashboard`` request. - - Attributes: - name (str): - Required. The resource name of the Dashboard. The format is - one of: - - - ``dashboards/[DASHBOARD_ID]`` (for system dashboards) - - ``projects/[PROJECT_ID_OR_NUMBER]/dashboards/[DASHBOARD_ID]`` - (for custom dashboards). - """ - - name = proto.Field(proto.STRING, number=1) - - -class DeleteDashboardRequest(proto.Message): - r"""The ``DeleteDashboard`` request. - - Attributes: - name (str): - Required. The resource name of the Dashboard. The format is: - - :: - - projects/[PROJECT_ID_OR_NUMBER]/dashboards/[DASHBOARD_ID] - """ - - name = proto.Field(proto.STRING, number=1) - - -class UpdateDashboardRequest(proto.Message): - r"""The ``UpdateDashboard`` request. - - Attributes: - dashboard (~.gmd_dashboard.Dashboard): - Required. The dashboard that will replace the - existing dashboard. - """ - - dashboard = proto.Field( - proto.MESSAGE, - number=1, - message=gmd_dashboard.Dashboard, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/layouts.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/layouts.py deleted file mode 100644 index 30937b29bd27..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/layouts.py +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import widget - -__protobuf__ = proto.module( - package="google.monitoring.dashboard.v1", - manifest={ - "GridLayout", - "RowLayout", - "ColumnLayout", - }, -) - - -class GridLayout(proto.Message): - r"""A basic layout divides the available space into vertical - columns of equal width and arranges a list of widgets using a - row-first strategy. - - Attributes: - columns (int): - The number of columns into which the view's - width is divided. If omitted or set to zero, a - system default will be used while rendering. - widgets (Sequence[~.widget.Widget]): - The informational elements that are arranged - into the columns row-first. - """ - - columns = proto.Field(proto.INT64, number=1) - - widgets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=widget.Widget, - ) - - -class RowLayout(proto.Message): - r"""A simplified layout that divides the available space into - rows and arranges a set of widgets horizontally in each row. - - Attributes: - rows (Sequence[~.layouts.RowLayout.Row]): - The rows of content to display. - """ - - class Row(proto.Message): - r"""Defines the layout properties and content for a row. - - Attributes: - weight (int): - The relative weight of this row. The row - weight is used to adjust the height of rows on - the screen (relative to peers). Greater the - weight, greater the height of the row on the - screen. If omitted, a value of 1 is used while - rendering. - widgets (Sequence[~.widget.Widget]): - The display widgets arranged horizontally in - this row. - """ - - weight = proto.Field(proto.INT64, number=1) - - widgets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=widget.Widget, - ) - - rows = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Row, - ) - - -class ColumnLayout(proto.Message): - r"""A simplified layout that divides the available space into - vertical columns and arranges a set of widgets vertically in - each column. - - Attributes: - columns (Sequence[~.layouts.ColumnLayout.Column]): - The columns of content to display. - """ - - class Column(proto.Message): - r"""Defines the layout properties and content for a column. - - Attributes: - weight (int): - The relative weight of this column. The - column weight is used to adjust the width of - columns on the screen (relative to peers). - Greater the weight, greater the width of the - column on the screen. If omitted, a value of 1 - is used while rendering. - widgets (Sequence[~.widget.Widget]): - The display widgets arranged vertically in - this column. - """ - - weight = proto.Field(proto.INT64, number=1) - - widgets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=widget.Widget, - ) - - columns = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Column, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/metrics.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/metrics.py deleted file mode 100644 index a3b435697b1c..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/metrics.py +++ /dev/null @@ -1,271 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import common - -__protobuf__ = proto.module( - package="google.monitoring.dashboard.v1", - manifest={ - "SparkChartType", - "TimeSeriesQuery", - "TimeSeriesFilter", - "TimeSeriesFilterRatio", - "Threshold", - }, -) - - -class SparkChartType(proto.Enum): - r"""Defines the possible types of spark chart supported by the - ``Scorecard``. - """ - - SPARK_CHART_TYPE_UNSPECIFIED = 0 - SPARK_LINE = 1 - SPARK_BAR = 2 - - -class TimeSeriesQuery(proto.Message): - r"""TimeSeriesQuery collects the set of supported methods for - querying time series data from the Stackdriver metrics API. - - Attributes: - time_series_filter (~.metrics.TimeSeriesFilter): - Filter parameters to fetch time series. - time_series_filter_ratio (~.metrics.TimeSeriesFilterRatio): - Parameters to fetch a ratio between two time - series filters. - time_series_query_language (str): - A query used to fetch time series. - unit_override (str): - The unit of data contained in fetched time series. If - non-empty, this unit will override any unit that accompanies - fetched data. The format is the same as the - ```unit`` `__ - field in ``MetricDescriptor``. - """ - - time_series_filter = proto.Field( - proto.MESSAGE, - number=1, - oneof="source", - message="TimeSeriesFilter", - ) - - time_series_filter_ratio = proto.Field( - proto.MESSAGE, - number=2, - oneof="source", - message="TimeSeriesFilterRatio", - ) - - time_series_query_language = proto.Field(proto.STRING, number=3, oneof="source") - - unit_override = proto.Field(proto.STRING, number=5) - - -class TimeSeriesFilter(proto.Message): - r"""A filter that defines a subset of time series data that is displayed - in a widget. Time series data is fetched using the - ```ListTimeSeries`` `__ - method. - - Attributes: - filter (str): - Required. The `monitoring - filter `__ - that identifies the metric types, resources, and projects to - query. - aggregation (~.common.Aggregation): - By default, the raw time series data is - returned. Use this field to combine multiple - time series for different views of the data. - secondary_aggregation (~.common.Aggregation): - Apply a second aggregation after ``aggregation`` is applied. - pick_time_series_filter (~.common.PickTimeSeriesFilter): - Ranking based time series filter. - statistical_time_series_filter (~.common.StatisticalTimeSeriesFilter): - Statistics based time series filter. - Note: This field is deprecated and completely - ignored by the API. - """ - - filter = proto.Field(proto.STRING, number=1) - - aggregation = proto.Field( - proto.MESSAGE, - number=2, - message=common.Aggregation, - ) - - secondary_aggregation = proto.Field( - proto.MESSAGE, - number=3, - message=common.Aggregation, - ) - - pick_time_series_filter = proto.Field( - proto.MESSAGE, - number=4, - oneof="output_filter", - message=common.PickTimeSeriesFilter, - ) - - statistical_time_series_filter = proto.Field( - proto.MESSAGE, - number=5, - oneof="output_filter", - message=common.StatisticalTimeSeriesFilter, - ) - - -class TimeSeriesFilterRatio(proto.Message): - r"""A pair of time series filters that define a ratio - computation. The output time series is the pair-wise division of - each aligned element from the numerator and denominator time - series. - - Attributes: - numerator (~.metrics.TimeSeriesFilterRatio.RatioPart): - The numerator of the ratio. - denominator (~.metrics.TimeSeriesFilterRatio.RatioPart): - The denominator of the ratio. - secondary_aggregation (~.common.Aggregation): - Apply a second aggregation after the ratio is - computed. - pick_time_series_filter (~.common.PickTimeSeriesFilter): - Ranking based time series filter. - statistical_time_series_filter (~.common.StatisticalTimeSeriesFilter): - Statistics based time series filter. - Note: This field is deprecated and completely - ignored by the API. - """ - - class RatioPart(proto.Message): - r"""Describes a query to build the numerator or denominator of a - TimeSeriesFilterRatio. - - Attributes: - filter (str): - Required. The `monitoring - filter `__ - that identifies the metric types, resources, and projects to - query. - aggregation (~.common.Aggregation): - By default, the raw time series data is - returned. Use this field to combine multiple - time series for different views of the data. - """ - - filter = proto.Field(proto.STRING, number=1) - - aggregation = proto.Field( - proto.MESSAGE, - number=2, - message=common.Aggregation, - ) - - numerator = proto.Field( - proto.MESSAGE, - number=1, - message=RatioPart, - ) - - denominator = proto.Field( - proto.MESSAGE, - number=2, - message=RatioPart, - ) - - secondary_aggregation = proto.Field( - proto.MESSAGE, - number=3, - message=common.Aggregation, - ) - - pick_time_series_filter = proto.Field( - proto.MESSAGE, - number=4, - oneof="output_filter", - message=common.PickTimeSeriesFilter, - ) - - statistical_time_series_filter = proto.Field( - proto.MESSAGE, - number=5, - oneof="output_filter", - message=common.StatisticalTimeSeriesFilter, - ) - - -class Threshold(proto.Message): - r"""Defines a threshold for categorizing time series values. - - Attributes: - label (str): - A label for the threshold. - value (float): - The value of the threshold. The value should - be defined in the native scale of the metric. - color (~.metrics.Threshold.Color): - The state color for this threshold. Color is - not allowed in a XyChart. - direction (~.metrics.Threshold.Direction): - The direction for the current threshold. - Direction is not allowed in a XyChart. - """ - - class Color(proto.Enum): - r"""The color suggests an interpretation to the viewer when - actual values cross the threshold. Comments on each color - provide UX guidance on how users can be expected to interpret a - given state color. - """ - - COLOR_UNSPECIFIED = 0 - YELLOW = 4 - RED = 6 - - class Direction(proto.Enum): - r"""Whether the threshold is considered crossed by an actual - value above or below its threshold value. - """ - - DIRECTION_UNSPECIFIED = 0 - ABOVE = 1 - BELOW = 2 - - label = proto.Field(proto.STRING, number=1) - - value = proto.Field(proto.DOUBLE, number=2) - - color = proto.Field( - proto.ENUM, - number=3, - enum=Color, - ) - - direction = proto.Field( - proto.ENUM, - number=4, - enum=Direction, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/scorecard.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/scorecard.py deleted file mode 100644 index 6a10a748c932..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/scorecard.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore -from google.protobuf import duration_pb2 as duration # type: ignore - -from google.monitoring.dashboard_v1.types import metrics - -__protobuf__ = proto.module( - package="google.monitoring.dashboard.v1", - manifest={ - "Scorecard", - }, -) - - -class Scorecard(proto.Message): - r"""A widget showing the latest value of a metric, and how this - value relates to one or more thresholds. - - Attributes: - time_series_query (~.metrics.TimeSeriesQuery): - Required. Fields for querying time series - data from the Stackdriver metrics API. - gauge_view (~.scorecard.Scorecard.GaugeView): - Will cause the scorecard to show a gauge - chart. - spark_chart_view (~.scorecard.Scorecard.SparkChartView): - Will cause the scorecard to show a spark - chart. - thresholds (Sequence[~.metrics.Threshold]): - The thresholds used to determine the state of - the scorecard given the time series' current - value. For an actual value x, the scorecard is - in a danger state if x is less than or equal to - a danger threshold that triggers below, or - greater than or equal to a danger threshold that - triggers above. Similarly, if x is above/below a - warning threshold that triggers above/below, - then the scorecard is in a warning state - - unless x also puts it in a danger state. (Danger - trumps warning.) - As an example, consider a scorecard with the - following four thresholds: { - value: 90, - category: 'DANGER', - trigger: 'ABOVE', - }, - { - value: 70, - category: 'WARNING', - trigger: 'ABOVE', - }, - { - value: 10, - category: 'DANGER', - trigger: 'BELOW', - }, - { - value: 20, - category: 'WARNING', - trigger: 'BELOW', - } - - Then: values less than or equal to 10 would put - the scorecard in a DANGER state, values greater - than 10 but less than or equal to 20 a WARNING - state, values strictly between 20 and 70 an OK - state, values greater than or equal to 70 but - less than 90 a WARNING state, and values greater - than or equal to 90 a DANGER state. - """ - - class GaugeView(proto.Message): - r"""A gauge chart shows where the current value sits within a - pre-defined range. The upper and lower bounds should define the - possible range of values for the scorecard's query (inclusive). - - Attributes: - lower_bound (float): - The lower bound for this gauge chart. The - value of the chart should always be greater than - or equal to this. - upper_bound (float): - The upper bound for this gauge chart. The - value of the chart should always be less than or - equal to this. - """ - - lower_bound = proto.Field(proto.DOUBLE, number=1) - - upper_bound = proto.Field(proto.DOUBLE, number=2) - - class SparkChartView(proto.Message): - r"""A sparkChart is a small chart suitable for inclusion in a - table-cell or inline in text. This message contains the - configuration for a sparkChart to show up on a Scorecard, - showing recent trends of the scorecard's timeseries. - - Attributes: - spark_chart_type (~.metrics.SparkChartType): - Required. The type of sparkchart to show in - this chartView. - min_alignment_period (~.duration.Duration): - The lower bound on data point frequency in - the chart implemented by specifying the minimum - alignment period to use in a time series query. - For example, if the data is published once every - 10 minutes it would not make sense to fetch and - align data at one minute intervals. This field - is optional and exists only as a hint. - """ - - spark_chart_type = proto.Field( - proto.ENUM, - number=1, - enum=metrics.SparkChartType, - ) - - min_alignment_period = proto.Field( - proto.MESSAGE, - number=2, - message=duration.Duration, - ) - - time_series_query = proto.Field( - proto.MESSAGE, - number=1, - message=metrics.TimeSeriesQuery, - ) - - gauge_view = proto.Field( - proto.MESSAGE, - number=4, - oneof="data_view", - message=GaugeView, - ) - - spark_chart_view = proto.Field( - proto.MESSAGE, - number=5, - oneof="data_view", - message=SparkChartView, - ) - - thresholds = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=metrics.Threshold, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/text.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/text.py deleted file mode 100644 index 81973f4fbfed..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/text.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore - -__protobuf__ = proto.module( - package="google.monitoring.dashboard.v1", - manifest={ - "Text", - }, -) - - -class Text(proto.Message): - r"""A widget that displays textual content. - - Attributes: - content (str): - The text content to be displayed. - format (~.text.Text.Format): - How the text content is formatted. - """ - - class Format(proto.Enum): - r"""The format type of the text content.""" - - FORMAT_UNSPECIFIED = 0 - MARKDOWN = 1 - RAW = 2 - - content = proto.Field(proto.STRING, number=1) - - format = proto.Field( - proto.ENUM, - number=2, - enum=Format, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/widget.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/widget.py deleted file mode 100644 index 2aa7990f5136..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/widget.py +++ /dev/null @@ -1,82 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - -from google.monitoring.dashboard_v1.types import scorecard as gmd_scorecard -from google.monitoring.dashboard_v1.types import text as gmd_text -from google.monitoring.dashboard_v1.types import xychart - -__protobuf__ = proto.module( - package="google.monitoring.dashboard.v1", - manifest={ - "Widget", - }, -) - - -class Widget(proto.Message): - r"""Widget contains a single dashboard component and - configuration of how to present the component in the dashboard. - - Attributes: - title (str): - Optional. The title of the widget. - xy_chart (~.xychart.XyChart): - A chart of time series data. - scorecard (~.gmd_scorecard.Scorecard): - A scorecard summarizing time series data. - text (~.gmd_text.Text): - A raw string or markdown displaying textual - content. - blank (~.empty.Empty): - A blank space. - """ - - title = proto.Field(proto.STRING, number=1) - - xy_chart = proto.Field( - proto.MESSAGE, - number=2, - oneof="content", - message=xychart.XyChart, - ) - - scorecard = proto.Field( - proto.MESSAGE, - number=3, - oneof="content", - message=gmd_scorecard.Scorecard, - ) - - text = proto.Field( - proto.MESSAGE, - number=4, - oneof="content", - message=gmd_text.Text, - ) - - blank = proto.Field( - proto.MESSAGE, - number=5, - oneof="content", - message=empty.Empty, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/xychart.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/xychart.py deleted file mode 100644 index 84e10300f0b3..000000000000 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/types/xychart.py +++ /dev/null @@ -1,196 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore -from google.protobuf import duration_pb2 as duration # type: ignore - -from google.monitoring.dashboard_v1.types import metrics - -__protobuf__ = proto.module( - package="google.monitoring.dashboard.v1", - manifest={ - "XyChart", - "ChartOptions", - }, -) - - -class XyChart(proto.Message): - r"""A chart that displays data on a 2D (X and Y axes) plane. - - Attributes: - data_sets (Sequence[~.xychart.XyChart.DataSet]): - Required. The data displayed in this chart. - timeshift_duration (~.duration.Duration): - The duration used to display a comparison - chart. A comparison chart simultaneously shows - values from two similar-length time periods - (e.g., week-over-week metrics). - The duration must be positive, and it can only - be applied to charts with data sets of LINE plot - type. - thresholds (Sequence[~.metrics.Threshold]): - Threshold lines drawn horizontally across the - chart. - x_axis (~.xychart.XyChart.Axis): - The properties applied to the X axis. - y_axis (~.xychart.XyChart.Axis): - The properties applied to the Y axis. - chart_options (~.xychart.ChartOptions): - Display options for the chart. - """ - - class DataSet(proto.Message): - r"""Groups a time series query definition with charting options. - - Attributes: - time_series_query (~.metrics.TimeSeriesQuery): - Required. Fields for querying time series - data from the Stackdriver metrics API. - plot_type (~.xychart.XyChart.DataSet.PlotType): - How this data should be plotted on the chart. - legend_template (str): - A template string for naming ``TimeSeries`` in the resulting - data set. This should be a string with interpolations of the - form ``${label_name}``, which will resolve to the label's - value. - min_alignment_period (~.duration.Duration): - Optional. The lower bound on data point frequency for this - data set, implemented by specifying the minimum alignment - period to use in a time series query For example, if the - data is published once every 10 minutes, the - ``min_alignment_period`` should be at least 10 minutes. It - would not make sense to fetch and align data at one minute - intervals. - """ - - class PlotType(proto.Enum): - r"""The types of plotting strategies for data sets.""" - - PLOT_TYPE_UNSPECIFIED = 0 - LINE = 1 - STACKED_AREA = 2 - STACKED_BAR = 3 - HEATMAP = 4 - - time_series_query = proto.Field( - proto.MESSAGE, - number=1, - message=metrics.TimeSeriesQuery, - ) - - plot_type = proto.Field( - proto.ENUM, - number=2, - enum="XyChart.DataSet.PlotType", - ) - - legend_template = proto.Field(proto.STRING, number=3) - - min_alignment_period = proto.Field( - proto.MESSAGE, - number=4, - message=duration.Duration, - ) - - class Axis(proto.Message): - r"""A chart axis. - - Attributes: - label (str): - The label of the axis. - scale (~.xychart.XyChart.Axis.Scale): - The axis scale. By default, a linear scale is - used. - """ - - class Scale(proto.Enum): - r"""Types of scales used in axes.""" - - SCALE_UNSPECIFIED = 0 - LINEAR = 1 - LOG10 = 2 - - label = proto.Field(proto.STRING, number=1) - - scale = proto.Field( - proto.ENUM, - number=2, - enum="XyChart.Axis.Scale", - ) - - data_sets = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=DataSet, - ) - - timeshift_duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration.Duration, - ) - - thresholds = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=metrics.Threshold, - ) - - x_axis = proto.Field( - proto.MESSAGE, - number=6, - message=Axis, - ) - - y_axis = proto.Field( - proto.MESSAGE, - number=7, - message=Axis, - ) - - chart_options = proto.Field( - proto.MESSAGE, - number=8, - message="ChartOptions", - ) - - -class ChartOptions(proto.Message): - r"""Options to control visual rendering of a chart. - - Attributes: - mode (~.xychart.ChartOptions.Mode): - The chart mode. - """ - - class Mode(proto.Enum): - r"""Chart mode options.""" - - MODE_UNSPECIFIED = 0 - COLOR = 1 - X_RAY = 2 - STATS = 3 - - mode = proto.Field( - proto.ENUM, - number=1, - enum=Mode, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-monitoring-dashboards/tests/unit/gapic/dashboard_v1/__init__.py b/packages/google-cloud-monitoring-dashboards/tests/unit/gapic/dashboard_v1/__init__.py deleted file mode 100644 index e8e1c3845db5..000000000000 --- a/packages/google-cloud-monitoring-dashboards/tests/unit/gapic/dashboard_v1/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- 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. -# diff --git a/packages/google-cloud-monitoring-dashboards/tests/unit/gapic/dashboard_v1/test_dashboards_service.py b/packages/google-cloud-monitoring-dashboards/tests/unit/gapic/dashboard_v1/test_dashboards_service.py deleted file mode 100644 index fc37b03fb361..000000000000 --- a/packages/google-cloud-monitoring-dashboards/tests/unit/gapic/dashboard_v1/test_dashboards_service.py +++ /dev/null @@ -1,2467 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import asyncio -import os - -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import math - -import google.auth -import grpc -import pytest -from google.api_core import ( - client_options, - gapic_v1, - grpc_helpers, - grpc_helpers_async, - path_template, -) -from google.api_core import exceptions as core_exceptions -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import ( - duration_pb2, # type: ignore - empty_pb2, # type: ignore -) -from grpc.experimental import aio -from proto.marshal.rules import wrappers -from proto.marshal.rules.dates import DurationRule, TimestampRule - -from google.cloud.monitoring_dashboard_v1.services.dashboards_service import ( - DashboardsServiceAsyncClient, - DashboardsServiceClient, - pagers, - transports, -) -from google.cloud.monitoring_dashboard_v1.types import ( - alertchart, - collapsible_group, - common, - dashboard, - dashboard_filter, - dashboards_service, - layouts, - logs_panel, - metrics, - scorecard, - table, - table_display_options, - text, - widget, - xychart, -) - - -@pytest.fixture(autouse=True) -def set_event_loop(): - try: - asyncio.get_running_loop() - yield - except RuntimeError: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - yield - finally: - loop.close() - asyncio.set_event_loop(None) - - -# Anonymous Credentials with universe domain property. If no universe domain is provided, then -# the default universe domain is "googleapis.com". -class _AnonymousCredentialsWithUniverseDomain(ga_credentials.AnonymousCredentials): - def __init__(self, universe_domain="googleapis.com"): - super(_AnonymousCredentialsWithUniverseDomain, self).__init__() - self._universe_domain = universe_domain - - @property - def universe_domain(self): - return self._universe_domain - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DashboardsServiceClient._get_default_mtls_endpoint(None) is None - assert ( - DashboardsServiceClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - DashboardsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - DashboardsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - DashboardsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - DashboardsServiceClient._get_default_mtls_endpoint(non_googleapi) - == non_googleapi - ) - - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (DashboardsServiceClient, "grpc"), - (DashboardsServiceAsyncClient, "grpc_asyncio"), - ], -) -def test_dashboards_service_client_from_service_account_info( - client_class, transport_name -): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ("monitoring.googleapis.com:443") - - -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.DashboardsServiceGrpcTransport, "grpc"), - (transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - ], -) -def test_dashboards_service_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (DashboardsServiceClient, "grpc"), - (DashboardsServiceAsyncClient, "grpc_asyncio"), - ], -) -def test_dashboards_service_client_from_service_account_file( - client_class, transport_name -): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: - factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ("monitoring.googleapis.com:443") - - -def test_dashboards_service_client_get_transport_class(): - transport = DashboardsServiceClient.get_transport_class() - available_transports = [ - transports.DashboardsServiceGrpcTransport, - ] - assert transport in available_transports - - transport = DashboardsServiceClient.get_transport_class("grpc") - assert transport == transports.DashboardsServiceGrpcTransport - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc"), - ( - DashboardsServiceAsyncClient, - transports.DashboardsServiceGrpcAsyncIOTransport, - "grpc_asyncio", - ), - ], -) -@mock.patch.object( - DashboardsServiceClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(DashboardsServiceClient), -) -@mock.patch.object( - DashboardsServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(DashboardsServiceAsyncClient), -) -def test_dashboards_service_client_client_options( - client_class, transport_class, transport_name -): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(DashboardsServiceClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(DashboardsServiceClient, "get_transport_class") as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - ( - DashboardsServiceClient, - transports.DashboardsServiceGrpcTransport, - "grpc", - "true", - ), - ( - DashboardsServiceAsyncClient, - transports.DashboardsServiceGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - ( - DashboardsServiceClient, - transports.DashboardsServiceGrpcTransport, - "grpc", - "false", - ), - ( - DashboardsServiceAsyncClient, - transports.DashboardsServiceGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - ], -) -@mock.patch.object( - DashboardsServiceClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(DashboardsServiceClient), -) -@mock.patch.object( - DashboardsServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(DashboardsServiceAsyncClient), -) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_dashboards_service_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize( - "client_class", [DashboardsServiceClient, DashboardsServiceAsyncClient] -) -@mock.patch.object( - DashboardsServiceClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(DashboardsServiceClient), -) -@mock.patch.object( - DashboardsServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(DashboardsServiceAsyncClient), -) -def test_dashboards_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc"), - ( - DashboardsServiceAsyncClient, - transports.DashboardsServiceGrpcAsyncIOTransport, - "grpc_asyncio", - ), - ], -) -def test_dashboards_service_client_client_options_scopes( - client_class, transport_class, transport_name -): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - DashboardsServiceClient, - transports.DashboardsServiceGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - DashboardsServiceAsyncClient, - transports.DashboardsServiceGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_dashboards_service_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): - # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") - - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -def test_dashboards_service_client_client_options_from_dict(): - with mock.patch( - "google.cloud.monitoring_dashboard_v1.services.dashboards_service.transports.DashboardsServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = DashboardsServiceClient( - client_options={"api_endpoint": "squid.clam.whelk"} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - DashboardsServiceClient, - transports.DashboardsServiceGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - DashboardsServiceAsyncClient, - transports.DashboardsServiceGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_dashboards_service_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): - # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") - - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with ( - mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, - mock.patch.object(google.auth, "default", autospec=True) as adc, - mock.patch.object(grpc_helpers, "create_channel") as create_channel, - ): - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "monitoring.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ), - scopes=None, - default_host="monitoring.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "request_type", - [ - dashboards_service.CreateDashboardRequest, - dict, - ], -) -def test_create_dashboard(request_type, transport: str = "grpc"): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_dashboard), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = dashboard.Dashboard( - name="name_value", - display_name="display_name_value", - etag="etag_value", - grid_layout=layouts.GridLayout(columns=769), - ) - response = client.create_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.CreateDashboardRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_dashboard), "__call__") as call: - client.create_dashboard() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.CreateDashboardRequest() - - -@pytest.mark.asyncio -async def test_create_dashboard_async( - transport: str = "grpc_asyncio", - request_type=dashboards_service.CreateDashboardRequest, -): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_dashboard), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - dashboard.Dashboard( - name="name_value", - display_name="display_name_value", - etag="etag_value", - ) - ) - response = await client.create_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.CreateDashboardRequest() - - # 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" - - -@pytest.mark.asyncio -async def test_create_dashboard_async_from_dict(): - await test_create_dashboard_async(request_type=dict) - - -def test_create_dashboard_field_headers(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.CreateDashboardRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_dashboard), "__call__") as call: - call.return_value = dashboard.Dashboard() - client.create_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_create_dashboard_field_headers_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.CreateDashboardRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_dashboard), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) - await client.create_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -@pytest.mark.parametrize( - "request_type", - [ - dashboards_service.ListDashboardsRequest, - dict, - ], -) -def test_list_dashboards(request_type, transport: str = "grpc"): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = dashboards_service.ListDashboardsResponse( - next_page_token="next_page_token_value", - ) - response = client.list_dashboards(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.ListDashboardsRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: - client.list_dashboards() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.ListDashboardsRequest() - - -@pytest.mark.asyncio -async def test_list_dashboards_async( - transport: str = "grpc_asyncio", - request_type=dashboards_service.ListDashboardsRequest, -): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - dashboards_service.ListDashboardsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_dashboards(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.ListDashboardsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDashboardsAsyncPager) - assert response.next_page_token == "next_page_token_value" - - -@pytest.mark.asyncio -async def test_list_dashboards_async_from_dict(): - await test_list_dashboards_async(request_type=dict) - - -def test_list_dashboards_field_headers(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.ListDashboardsRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: - call.return_value = dashboards_service.ListDashboardsResponse() - client.list_dashboards(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_list_dashboards_field_headers_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.ListDashboardsRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - dashboards_service.ListDashboardsResponse() - ) - await client.list_dashboards(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -def test_list_dashboards_pager(transport_name: str = "grpc"): - client = DashboardsServiceClient( - credentials=_AnonymousCredentialsWithUniverseDomain(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_dashboards(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, dashboard.Dashboard) for i in results) - - -def test_list_dashboards_pages(transport_name: str = "grpc"): - client = DashboardsServiceClient( - credentials=_AnonymousCredentialsWithUniverseDomain(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - pages = list(client.list_dashboards(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_dashboards_async_pager(): - client = DashboardsServiceAsyncClient( - credentials=_AnonymousCredentialsWithUniverseDomain(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_dashboards( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, dashboard.Dashboard) for i in responses) - - -@pytest.mark.asyncio -async def test_list_dashboards_async_pages(): - client = DashboardsServiceAsyncClient( - credentials=_AnonymousCredentialsWithUniverseDomain(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.list_dashboards(request={}) - ).pages: # pragma: no branch - pages.append(page_) - 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(request_type, transport: str = "grpc"): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_dashboard), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = dashboard.Dashboard( - name="name_value", - display_name="display_name_value", - etag="etag_value", - grid_layout=layouts.GridLayout(columns=769), - ) - response = client.get_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.GetDashboardRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_dashboard), "__call__") as call: - client.get_dashboard() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.GetDashboardRequest() - - -@pytest.mark.asyncio -async def test_get_dashboard_async( - transport: str = "grpc_asyncio", request_type=dashboards_service.GetDashboardRequest -): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_dashboard), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - dashboard.Dashboard( - name="name_value", - display_name="display_name_value", - etag="etag_value", - ) - ) - response = await client.get_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.GetDashboardRequest() - - # 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" - - -@pytest.mark.asyncio -async def test_get_dashboard_async_from_dict(): - await test_get_dashboard_async(request_type=dict) - - -def test_get_dashboard_field_headers(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.GetDashboardRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_dashboard), "__call__") as call: - call.return_value = dashboard.Dashboard() - client.get_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_dashboard_field_headers_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.GetDashboardRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_dashboard), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) - await client.get_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.parametrize( - "request_type", - [ - dashboards_service.DeleteDashboardRequest, - dict, - ], -) -def test_delete_dashboard(request_type, transport: str = "grpc"): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_dashboard), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.DeleteDashboardRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_dashboard_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_dashboard), "__call__") as call: - client.delete_dashboard() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.DeleteDashboardRequest() - - -@pytest.mark.asyncio -async def test_delete_dashboard_async( - transport: str = "grpc_asyncio", - request_type=dashboards_service.DeleteDashboardRequest, -): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_dashboard), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.DeleteDashboardRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_dashboard_async_from_dict(): - await test_delete_dashboard_async(request_type=dict) - - -def test_delete_dashboard_field_headers(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.DeleteDashboardRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_dashboard), "__call__") as call: - call.return_value = None - client.delete_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_delete_dashboard_field_headers_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.DeleteDashboardRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_dashboard), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.parametrize( - "request_type", - [ - dashboards_service.UpdateDashboardRequest, - dict, - ], -) -def test_update_dashboard(request_type, transport: str = "grpc"): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_dashboard), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = dashboard.Dashboard( - name="name_value", - display_name="display_name_value", - etag="etag_value", - grid_layout=layouts.GridLayout(columns=769), - ) - response = client.update_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.UpdateDashboardRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_dashboard), "__call__") as call: - client.update_dashboard() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.UpdateDashboardRequest() - - -@pytest.mark.asyncio -async def test_update_dashboard_async( - transport: str = "grpc_asyncio", - request_type=dashboards_service.UpdateDashboardRequest, -): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_dashboard), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - dashboard.Dashboard( - name="name_value", - display_name="display_name_value", - etag="etag_value", - ) - ) - response = await client.update_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.UpdateDashboardRequest() - - # 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" - - -@pytest.mark.asyncio -async def test_update_dashboard_async_from_dict(): - await test_update_dashboard_async(request_type=dict) - - -def test_update_dashboard_field_headers(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.UpdateDashboardRequest() - - request.dashboard.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_dashboard), "__call__") as call: - call.return_value = dashboard.Dashboard() - client.update_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "dashboard.name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_update_dashboard_field_headers_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.UpdateDashboardRequest() - - request.dashboard.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_dashboard), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) - await client.update_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "dashboard.name=name_value", - ) in kw["metadata"] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=_AnonymousCredentialsWithUniverseDomain(), - ) - with pytest.raises(ValueError): - client = DashboardsServiceClient( - credentials=_AnonymousCredentialsWithUniverseDomain(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=_AnonymousCredentialsWithUniverseDomain(), - ) - with pytest.raises(ValueError): - client = DashboardsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=_AnonymousCredentialsWithUniverseDomain(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DashboardsServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DashboardsServiceClient( - client_options=options, - credentials=_AnonymousCredentialsWithUniverseDomain(), - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=_AnonymousCredentialsWithUniverseDomain(), - ) - with pytest.raises(ValueError): - client = DashboardsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DashboardsServiceClient(transport=transport) - assert client.transport is transport - - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DashboardsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DashboardsServiceGrpcTransport, - transports.DashboardsServiceGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - ], -) -def test_transport_kind(transport_name): - transport = DashboardsServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DashboardsServiceGrpcTransport, - ) - - -def test_dashboards_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DashboardsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) - - -def test_dashboards_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.monitoring_dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.DashboardsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_dashboard", - "list_dashboards", - "get_dashboard", - "delete_dashboard", - "update_dashboard", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_dashboards_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with ( - mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, - mock.patch( - "google.cloud.monitoring_dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport._prep_wrapped_messages" - ) as Transport, - ): - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DashboardsServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ), - quota_project_id="octopus", - ) - - -def test_dashboards_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with ( - mock.patch.object(google.auth, "default", autospec=True) as adc, - mock.patch( - "google.cloud.monitoring_dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport._prep_wrapped_messages" - ) as Transport, - ): - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DashboardsServiceTransport() - adc.assert_called_once() - - -def test_dashboards_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DashboardsServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DashboardsServiceGrpcTransport, - transports.DashboardsServiceGrpcAsyncIOTransport, - ], -) -def test_dashboards_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DashboardsServiceGrpcTransport, - transports.DashboardsServiceGrpcAsyncIOTransport, - ], -) -def test_dashboards_service_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DashboardsServiceGrpcTransport, grpc_helpers), - (transports.DashboardsServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_dashboards_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with ( - mock.patch.object(google.auth, "default", autospec=True) as adc, - mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel, - ): - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "monitoring.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ), - scopes=["1", "2"], - default_host="monitoring.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DashboardsServiceGrpcTransport, - transports.DashboardsServiceGrpcAsyncIOTransport, - ], -) -def test_dashboards_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) - - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - ], -) -def test_dashboards_service_host_no_port(transport_name): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="monitoring.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ("monitoring.googleapis.com:443") - - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - ], -) -def test_dashboards_service_host_with_port(transport_name): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="monitoring.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ("monitoring.googleapis.com:8000") - - -def test_dashboards_service_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DashboardsServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_dashboards_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DashboardsServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.DashboardsServiceGrpcTransport, - transports.DashboardsServiceGrpcAsyncIOTransport, - ], -) -def test_dashboards_service_transport_channel_mtls_with_client_cert_source( - transport_class, -): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.DashboardsServiceGrpcTransport, - transports.DashboardsServiceGrpcAsyncIOTransport, - ], -) -def test_dashboards_service_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_alert_policy_path(): - project = "squid" - alert_policy = "clam" - expected = "projects/{project}/alertPolicies/{alert_policy}".format( - project=project, - alert_policy=alert_policy, - ) - actual = DashboardsServiceClient.alert_policy_path(project, alert_policy) - assert expected == actual - - -def test_parse_alert_policy_path(): - expected = { - "project": "whelk", - "alert_policy": "octopus", - } - path = DashboardsServiceClient.alert_policy_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_alert_policy_path(path) - assert expected == actual - - -def test_dashboard_path(): - project = "oyster" - dashboard = "nudibranch" - expected = "projects/{project}/dashboards/{dashboard}".format( - project=project, - dashboard=dashboard, - ) - actual = DashboardsServiceClient.dashboard_path(project, dashboard) - assert expected == actual - - -def test_parse_dashboard_path(): - expected = { - "project": "cuttlefish", - "dashboard": "mussel", - } - path = DashboardsServiceClient.dashboard_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_dashboard_path(path) - assert expected == actual - - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = DashboardsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = DashboardsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = DashboardsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = DashboardsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = DashboardsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = DashboardsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format( - project=project, - ) - actual = DashboardsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = DashboardsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = DashboardsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = DashboardsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object( - transports.DashboardsServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object( - transports.DashboardsServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = DashboardsServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - "grpc", - ] - for transport in transports: - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport), - ( - DashboardsServiceAsyncClient, - transports.DashboardsServiceGrpcAsyncIOTransport, - ), - ], -) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/release-please-bulk-config.json b/release-please-bulk-config.json index d8cf190385ea..34637d4d7c08 100644 --- a/release-please-bulk-config.json +++ b/release-please-bulk-config.json @@ -2158,7 +2158,6 @@ "extra-files": [ "google/cloud/monitoring_dashboard/gapic_version.py", "google/cloud/monitoring_dashboard_v1/gapic_version.py", - "google/monitoring/dashboard_v1/gapic_version.py", { "jsonpath": "$.clientLibrary.version", "path": "samples/generated_samples/snippet_metadata_google.monitoring.dashboard.v1.json",