From 1d33db7ade09a6ee35e2a4b371bc2d3ba82c8e06 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 9 Jan 2023 11:05:04 -0500 Subject: [PATCH] feat: Added Snooze API support (#519) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Added Snooze API support PiperOrigin-RevId: 500543032 Source-Link: https://github.com/googleapis/googleapis/commit/d4864bf1425882fddb80ffb627c385ec22d1fd00 Source-Link: https://github.com/googleapis/googleapis-gen/commit/245031557f8852e8e089a6511f63fc226703fef9 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMjQ1MDMxNTU3Zjg4NTJlOGUwODlhNjUxMWY2M2ZjMjI2NzAzZmVmOSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * workaround docs issue Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- docs/monitoring_v3/services.rst | 1 + docs/monitoring_v3/snooze_service.rst | 10 + google/cloud/monitoring/__init__.py | 20 + google/cloud/monitoring_v3/__init__.py | 16 + .../cloud/monitoring_v3/gapic_metadata.json | 54 + .../services/snooze_service/__init__.py | 22 + .../services/snooze_service/async_client.py | 777 +++++ .../services/snooze_service/client.py | 1003 +++++++ .../services/snooze_service/pagers.py | 156 + .../snooze_service/transports/__init__.py | 33 + .../snooze_service/transports/base.py | 225 ++ .../snooze_service/transports/grpc.py | 354 +++ .../snooze_service/transports/grpc_asyncio.py | 356 +++ google/cloud/monitoring_v3/types/__init__.py | 16 + google/cloud/monitoring_v3/types/snooze.py | 103 + .../monitoring_v3/types/snooze_service.py | 233 ++ ...ated_snooze_service_create_snooze_async.py | 57 + ...rated_snooze_service_create_snooze_sync.py | 57 + ...nerated_snooze_service_get_snooze_async.py | 52 + ...enerated_snooze_service_get_snooze_sync.py | 52 + ...rated_snooze_service_list_snoozes_async.py | 53 + ...erated_snooze_service_list_snoozes_sync.py | 53 + ...ated_snooze_service_update_snooze_async.py | 56 + ...rated_snooze_service_update_snooze_sync.py | 56 + ...snippet_metadata_google.monitoring.v3.json | 662 ++++- scripts/fixup_monitoring_v3_keywords.py | 4 + .../monitoring_v3/test_snooze_service.py | 2575 +++++++++++++++++ 27 files changed, 7055 insertions(+), 1 deletion(-) create mode 100644 docs/monitoring_v3/snooze_service.rst create mode 100644 google/cloud/monitoring_v3/services/snooze_service/__init__.py create mode 100644 google/cloud/monitoring_v3/services/snooze_service/async_client.py create mode 100644 google/cloud/monitoring_v3/services/snooze_service/client.py create mode 100644 google/cloud/monitoring_v3/services/snooze_service/pagers.py create mode 100644 google/cloud/monitoring_v3/services/snooze_service/transports/__init__.py create mode 100644 google/cloud/monitoring_v3/services/snooze_service/transports/base.py create mode 100644 google/cloud/monitoring_v3/services/snooze_service/transports/grpc.py create mode 100644 google/cloud/monitoring_v3/services/snooze_service/transports/grpc_asyncio.py create mode 100644 google/cloud/monitoring_v3/types/snooze.py create mode 100644 google/cloud/monitoring_v3/types/snooze_service.py create mode 100644 samples/generated_samples/monitoring_v3_generated_snooze_service_create_snooze_async.py create mode 100644 samples/generated_samples/monitoring_v3_generated_snooze_service_create_snooze_sync.py create mode 100644 samples/generated_samples/monitoring_v3_generated_snooze_service_get_snooze_async.py create mode 100644 samples/generated_samples/monitoring_v3_generated_snooze_service_get_snooze_sync.py create mode 100644 samples/generated_samples/monitoring_v3_generated_snooze_service_list_snoozes_async.py create mode 100644 samples/generated_samples/monitoring_v3_generated_snooze_service_list_snoozes_sync.py create mode 100644 samples/generated_samples/monitoring_v3_generated_snooze_service_update_snooze_async.py create mode 100644 samples/generated_samples/monitoring_v3_generated_snooze_service_update_snooze_sync.py create mode 100644 tests/unit/gapic/monitoring_v3/test_snooze_service.py diff --git a/docs/monitoring_v3/services.rst b/docs/monitoring_v3/services.rst index 18a1eb15..37794072 100644 --- a/docs/monitoring_v3/services.rst +++ b/docs/monitoring_v3/services.rst @@ -9,4 +9,5 @@ Services for Google Cloud Monitoring v3 API notification_channel_service query_service service_monitoring_service + snooze_service uptime_check_service diff --git a/docs/monitoring_v3/snooze_service.rst b/docs/monitoring_v3/snooze_service.rst new file mode 100644 index 00000000..6e94fd1f --- /dev/null +++ b/docs/monitoring_v3/snooze_service.rst @@ -0,0 +1,10 @@ +SnoozeService +------------------------------- + +.. automodule:: google.cloud.monitoring_v3.services.snooze_service + :members: + :inherited-members: + +.. automodule:: google.cloud.monitoring_v3.services.snooze_service.pagers + :members: + :inherited-members: diff --git a/google/cloud/monitoring/__init__.py b/google/cloud/monitoring/__init__.py index 342e79c4..8d0c4b59 100644 --- a/google/cloud/monitoring/__init__.py +++ b/google/cloud/monitoring/__init__.py @@ -50,6 +50,12 @@ from google.cloud.monitoring_v3.services.service_monitoring_service.async_client import ( ServiceMonitoringServiceAsyncClient, ) +from google.cloud.monitoring_v3.services.snooze_service.client import ( + SnoozeServiceClient, +) +from google.cloud.monitoring_v3.services.snooze_service.async_client import ( + SnoozeServiceAsyncClient, +) from google.cloud.monitoring_v3.services.uptime_check_service.client import ( UptimeCheckServiceClient, ) @@ -189,6 +195,12 @@ UpdateServiceLevelObjectiveRequest, ) from google.cloud.monitoring_v3.types.service_service import UpdateServiceRequest +from google.cloud.monitoring_v3.types.snooze import Snooze +from google.cloud.monitoring_v3.types.snooze_service import CreateSnoozeRequest +from google.cloud.monitoring_v3.types.snooze_service import GetSnoozeRequest +from google.cloud.monitoring_v3.types.snooze_service import ListSnoozesRequest +from google.cloud.monitoring_v3.types.snooze_service import ListSnoozesResponse +from google.cloud.monitoring_v3.types.snooze_service import UpdateSnoozeRequest from google.cloud.monitoring_v3.types.span_context import SpanContext from google.cloud.monitoring_v3.types.uptime import InternalChecker from google.cloud.monitoring_v3.types.uptime import UptimeCheckConfig @@ -227,6 +239,8 @@ "QueryServiceAsyncClient", "ServiceMonitoringServiceClient", "ServiceMonitoringServiceAsyncClient", + "SnoozeServiceClient", + "SnoozeServiceAsyncClient", "UptimeCheckServiceClient", "UptimeCheckServiceAsyncClient", "AlertPolicy", @@ -311,6 +325,12 @@ "ListServicesResponse", "UpdateServiceLevelObjectiveRequest", "UpdateServiceRequest", + "Snooze", + "CreateSnoozeRequest", + "GetSnoozeRequest", + "ListSnoozesRequest", + "ListSnoozesResponse", + "UpdateSnoozeRequest", "SpanContext", "InternalChecker", "UptimeCheckConfig", diff --git a/google/cloud/monitoring_v3/__init__.py b/google/cloud/monitoring_v3/__init__.py index f7e8c19f..b8386245 100644 --- a/google/cloud/monitoring_v3/__init__.py +++ b/google/cloud/monitoring_v3/__init__.py @@ -30,6 +30,8 @@ from .services.query_service import QueryServiceAsyncClient from .services.service_monitoring_service import ServiceMonitoringServiceClient from .services.service_monitoring_service import ServiceMonitoringServiceAsyncClient +from .services.snooze_service import SnoozeServiceClient +from .services.snooze_service import SnoozeServiceAsyncClient from .services.uptime_check_service import UptimeCheckServiceClient from .services.uptime_check_service import UptimeCheckServiceAsyncClient @@ -115,6 +117,12 @@ from .types.service_service import ListServicesResponse from .types.service_service import UpdateServiceLevelObjectiveRequest from .types.service_service import UpdateServiceRequest +from .types.snooze import Snooze +from .types.snooze_service import CreateSnoozeRequest +from .types.snooze_service import GetSnoozeRequest +from .types.snooze_service import ListSnoozesRequest +from .types.snooze_service import ListSnoozesResponse +from .types.snooze_service import UpdateSnoozeRequest from .types.span_context import SpanContext from .types.uptime import InternalChecker from .types.uptime import UptimeCheckConfig @@ -137,6 +145,7 @@ "NotificationChannelServiceAsyncClient", "QueryServiceAsyncClient", "ServiceMonitoringServiceAsyncClient", + "SnoozeServiceAsyncClient", "UptimeCheckServiceAsyncClient", "Aggregation", "AlertPolicy", @@ -149,6 +158,7 @@ "CreateNotificationChannelRequest", "CreateServiceLevelObjectiveRequest", "CreateServiceRequest", + "CreateSnoozeRequest", "CreateTimeSeriesError", "CreateTimeSeriesRequest", "CreateTimeSeriesSummary", @@ -172,6 +182,7 @@ "GetNotificationChannelVerificationCodeResponse", "GetServiceLevelObjectiveRequest", "GetServiceRequest", + "GetSnoozeRequest", "GetUptimeCheckConfigRequest", "Group", "GroupResourceType", @@ -196,6 +207,8 @@ "ListServiceLevelObjectivesResponse", "ListServicesRequest", "ListServicesResponse", + "ListSnoozesRequest", + "ListSnoozesResponse", "ListTimeSeriesRequest", "ListTimeSeriesResponse", "ListUptimeCheckConfigsRequest", @@ -221,6 +234,8 @@ "ServiceLevelObjective", "ServiceMonitoringServiceClient", "ServiceTier", + "Snooze", + "SnoozeServiceClient", "SpanContext", "TextLocator", "TimeInterval", @@ -234,6 +249,7 @@ "UpdateNotificationChannelRequest", "UpdateServiceLevelObjectiveRequest", "UpdateServiceRequest", + "UpdateSnoozeRequest", "UpdateUptimeCheckConfigRequest", "UptimeCheckConfig", "UptimeCheckIp", diff --git a/google/cloud/monitoring_v3/gapic_metadata.json b/google/cloud/monitoring_v3/gapic_metadata.json index c4311709..bcb56c4a 100644 --- a/google/cloud/monitoring_v3/gapic_metadata.json +++ b/google/cloud/monitoring_v3/gapic_metadata.json @@ -499,6 +499,60 @@ } } }, + "SnoozeService": { + "clients": { + "grpc": { + "libraryClient": "SnoozeServiceClient", + "rpcs": { + "CreateSnooze": { + "methods": [ + "create_snooze" + ] + }, + "GetSnooze": { + "methods": [ + "get_snooze" + ] + }, + "ListSnoozes": { + "methods": [ + "list_snoozes" + ] + }, + "UpdateSnooze": { + "methods": [ + "update_snooze" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SnoozeServiceAsyncClient", + "rpcs": { + "CreateSnooze": { + "methods": [ + "create_snooze" + ] + }, + "GetSnooze": { + "methods": [ + "get_snooze" + ] + }, + "ListSnoozes": { + "methods": [ + "list_snoozes" + ] + }, + "UpdateSnooze": { + "methods": [ + "update_snooze" + ] + } + } + } + } + }, "UptimeCheckService": { "clients": { "grpc": { diff --git a/google/cloud/monitoring_v3/services/snooze_service/__init__.py b/google/cloud/monitoring_v3/services/snooze_service/__init__.py new file mode 100644 index 00000000..c750b0ce --- /dev/null +++ b/google/cloud/monitoring_v3/services/snooze_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SnoozeServiceClient +from .async_client import SnoozeServiceAsyncClient + +__all__ = ( + "SnoozeServiceClient", + "SnoozeServiceAsyncClient", +) diff --git a/google/cloud/monitoring_v3/services/snooze_service/async_client.py b/google/cloud/monitoring_v3/services/snooze_service/async_client.py new file mode 100644 index 00000000..f3ebf82f --- /dev/null +++ b/google/cloud/monitoring_v3/services/snooze_service/async_client.py @@ -0,0 +1,777 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.cloud.monitoring_v3 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.monitoring_v3.services.snooze_service import pagers +from google.cloud.monitoring_v3.types import common +from google.cloud.monitoring_v3.types import snooze +from google.cloud.monitoring_v3.types import snooze as gm_snooze +from google.cloud.monitoring_v3.types import snooze_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SnoozeServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SnoozeServiceGrpcAsyncIOTransport +from .client import SnoozeServiceClient + + +class SnoozeServiceAsyncClient: + """The SnoozeService API is used to temporarily prevent an alert + policy from generating alerts. A Snooze is a description of the + criteria under which one or more alert policies should not fire + alerts for the specified duration. + """ + + _client: SnoozeServiceClient + + DEFAULT_ENDPOINT = SnoozeServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SnoozeServiceClient.DEFAULT_MTLS_ENDPOINT + + alert_policy_path = staticmethod(SnoozeServiceClient.alert_policy_path) + parse_alert_policy_path = staticmethod(SnoozeServiceClient.parse_alert_policy_path) + snooze_path = staticmethod(SnoozeServiceClient.snooze_path) + parse_snooze_path = staticmethod(SnoozeServiceClient.parse_snooze_path) + common_billing_account_path = staticmethod( + SnoozeServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SnoozeServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SnoozeServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SnoozeServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SnoozeServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SnoozeServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(SnoozeServiceClient.common_project_path) + parse_common_project_path = staticmethod( + SnoozeServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(SnoozeServiceClient.common_location_path) + parse_common_location_path = staticmethod( + SnoozeServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SnoozeServiceAsyncClient: The constructed client. + """ + return SnoozeServiceClient.from_service_account_info.__func__(SnoozeServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @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: + SnoozeServiceAsyncClient: The constructed client. + """ + return SnoozeServiceClient.from_service_account_file.__func__(SnoozeServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SnoozeServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SnoozeServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SnoozeServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(SnoozeServiceClient).get_transport_class, type(SnoozeServiceClient) + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SnoozeServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the snooze 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, ~.SnoozeServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + 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_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SnoozeServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def create_snooze( + self, + request: Optional[Union[snooze_service.CreateSnoozeRequest, dict]] = None, + *, + parent: Optional[str] = None, + snooze: Optional[gm_snooze.Snooze] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gm_snooze.Snooze: + r"""Creates a ``Snooze`` that will prevent alerts, which match the + provided criteria, from being opened. The ``Snooze`` applies for + a specific time interval. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import monitoring_v3 + + async def sample_create_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceAsyncClient() + + # Initialize request argument(s) + snooze = monitoring_v3.Snooze() + snooze.name = "name_value" + snooze.display_name = "display_name_value" + + request = monitoring_v3.CreateSnoozeRequest( + parent="parent_value", + snooze=snooze, + ) + + # Make the request + response = await client.create_snooze(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.monitoring_v3.types.CreateSnoozeRequest, dict]]): + The request object. The message definition for creating + a `Snooze`. Users must provide the body of the `Snooze` + to be created but must omit the `Snooze` field, `name`. + parent (:class:`str`): + Required. The + `project `__ + in which a ``Snooze`` should be created. The format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER] + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + snooze (:class:`google.cloud.monitoring_v3.types.Snooze`): + Required. The ``Snooze`` to create. Omit the ``name`` + field, as it will be filled in by the API. + + This corresponds to the ``snooze`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.monitoring_v3.types.Snooze: + A Snooze will prevent any alerts from being opened, and close any that + are already open. The Snooze will work on alerts that + match the criteria defined in the Snooze. The Snooze + will be active from interval.start_time through + interval.end_time. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, snooze]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = snooze_service.CreateSnoozeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if snooze is not None: + request.snooze = snooze + + # 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_snooze, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_snoozes( + self, + request: Optional[Union[snooze_service.ListSnoozesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSnoozesAsyncPager: + r"""Lists the ``Snooze``\ s associated with a project. Can + optionally pass in ``filter``, which specifies predicates to + match ``Snooze``\ s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import monitoring_v3 + + async def sample_list_snoozes(): + # Create a client + client = monitoring_v3.SnoozeServiceAsyncClient() + + # Initialize request argument(s) + request = monitoring_v3.ListSnoozesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_snoozes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.monitoring_v3.types.ListSnoozesRequest, dict]]): + The request object. The message definition for listing + `Snooze`s associated with the given `parent`, satisfying + the optional `filter`. + parent (:class:`str`): + Required. The + `project `__ + whose ``Snooze``\ s should be listed. The format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER] + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.monitoring_v3.services.snooze_service.pagers.ListSnoozesAsyncPager: + The results of a successful ListSnoozes call, containing the matching + Snoozes. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = snooze_service.ListSnoozesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_snoozes, + default_retry=retries.Retry( + initial=0.1, + maximum=30.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSnoozesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_snooze( + self, + request: Optional[Union[snooze_service.GetSnoozeRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> snooze.Snooze: + r"""Retrieves a ``Snooze`` by ``name``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import monitoring_v3 + + async def sample_get_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceAsyncClient() + + # Initialize request argument(s) + request = monitoring_v3.GetSnoozeRequest( + name="name_value", + ) + + # Make the request + response = await client.get_snooze(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.monitoring_v3.types.GetSnoozeRequest, dict]]): + The request object. The message definition for + retrieving a `Snooze`. Users must specify the field, + `name`, which identifies the `Snooze`. + name (:class:`str`): + Required. The ID of the ``Snooze`` to retrieve. The + format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER]/snoozes/[SNOOZE_ID] + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.monitoring_v3.types.Snooze: + A Snooze will prevent any alerts from being opened, and close any that + are already open. The Snooze will work on alerts that + match the criteria defined in the Snooze. The Snooze + will be active from interval.start_time through + interval.end_time. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = snooze_service.GetSnoozeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_snooze, + default_retry=retries.Retry( + initial=0.1, + maximum=30.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_snooze( + self, + request: Optional[Union[snooze_service.UpdateSnoozeRequest, dict]] = None, + *, + snooze: Optional[gm_snooze.Snooze] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gm_snooze.Snooze: + r"""Updates a ``Snooze``, identified by its ``name``, with the + parameters in the given ``Snooze`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import monitoring_v3 + + async def sample_update_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceAsyncClient() + + # Initialize request argument(s) + snooze = monitoring_v3.Snooze() + snooze.name = "name_value" + snooze.display_name = "display_name_value" + + request = monitoring_v3.UpdateSnoozeRequest( + snooze=snooze, + ) + + # Make the request + response = await client.update_snooze(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.monitoring_v3.types.UpdateSnoozeRequest, dict]]): + The request object. The message definition for updating + a `Snooze`. The field, `snooze.name` identifies the + `Snooze` to be updated. The remainder of `snooze` gives + the content the `Snooze` in question will be assigned. + + What fields can be updated depends on the start time and + end time of the `Snooze`. + * end time is in the past: These `Snooze`s are + considered read-only and cannot be updated. + * start time is in the past and end time is in the + future: `display_name` and `interval.end_time` can + be updated. + * start time is in the future: `display_name`, + `interval.start_time` and `interval.end_time` can be + updated. + snooze (:class:`google.cloud.monitoring_v3.types.Snooze`): + Required. The ``Snooze`` to update. Must have the name + field present. + + This corresponds to the ``snooze`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The fields to update. + + For each field listed in ``update_mask``: + + - If the ``Snooze`` object supplied in the + ``UpdateSnoozeRequest`` has a value for that field, + the value of the field in the existing ``Snooze`` + will be set to the value of the field in the supplied + ``Snooze``. + - If the field does not have a value in the supplied + ``Snooze``, the field in the existing ``Snooze`` is + set to its default value. + + Fields not listed retain their existing value. + + The following are the field names that are accepted in + ``update_mask``: + + - ``display_name`` + - ``interval.start_time`` + - ``interval.end_time`` + + That said, the start time and end time of the ``Snooze`` + determines which fields can legally be updated. Before + attempting an update, users should consult the + documentation for ``UpdateSnoozeRequest``, which talks + about which fields can be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.monitoring_v3.types.Snooze: + A Snooze will prevent any alerts from being opened, and close any that + are already open. The Snooze will work on alerts that + match the criteria defined in the Snooze. The Snooze + will be active from interval.start_time through + interval.end_time. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([snooze, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = snooze_service.UpdateSnoozeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if snooze is not None: + request.snooze = snooze + if update_mask is not None: + request.update_mask = update_mask + + # 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_snooze, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("snooze.name", request.snooze.name),) + ), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("SnoozeServiceAsyncClient",) diff --git a/google/cloud/monitoring_v3/services/snooze_service/client.py b/google/cloud/monitoring_v3/services/snooze_service/client.py new file mode 100644 index 00000000..edc1150a --- /dev/null +++ b/google/cloud/monitoring_v3/services/snooze_service/client.py @@ -0,0 +1,1003 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +from google.cloud.monitoring_v3 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.monitoring_v3.services.snooze_service import pagers +from google.cloud.monitoring_v3.types import common +from google.cloud.monitoring_v3.types import snooze +from google.cloud.monitoring_v3.types import snooze as gm_snooze +from google.cloud.monitoring_v3.types import snooze_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SnoozeServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SnoozeServiceGrpcTransport +from .transports.grpc_asyncio import SnoozeServiceGrpcAsyncIOTransport + + +class SnoozeServiceClientMeta(type): + """Metaclass for the SnoozeService 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[SnoozeServiceTransport]] + _transport_registry["grpc"] = SnoozeServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SnoozeServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SnoozeServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: 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 SnoozeServiceClient(metaclass=SnoozeServiceClientMeta): + """The SnoozeService API is used to temporarily prevent an alert + policy from generating alerts. A Snooze is a description of the + criteria under which one or more alert policies should not fire + alerts for the specified duration. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts 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_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SnoozeServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @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: + SnoozeServiceClient: 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 + + @property + def transport(self) -> SnoozeServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SnoozeServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def alert_policy_path( + project: str, + alert_policy: str, + ) -> str: + """Returns a fully-qualified alert_policy string.""" + return "projects/{project}/alertPolicies/{alert_policy}".format( + project=project, + alert_policy=alert_policy, + ) + + @staticmethod + def parse_alert_policy_path(path: str) -> Dict[str, str]: + """Parses a alert_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/alertPolicies/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def snooze_path( + project: str, + snooze: str, + ) -> str: + """Returns a fully-qualified snooze string.""" + return "projects/{project}/snoozes/{snooze}".format( + project=project, + snooze=snooze, + ) + + @staticmethod + def parse_snooze_path(path: str) -> Dict[str, str]: + """Parses a snooze path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/snoozes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SnoozeServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the snooze 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, SnoozeServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options + ) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # 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, SnoozeServiceTransport): + # transport is a SnoozeServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + 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: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_snooze( + self, + request: Optional[Union[snooze_service.CreateSnoozeRequest, dict]] = None, + *, + parent: Optional[str] = None, + snooze: Optional[gm_snooze.Snooze] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gm_snooze.Snooze: + r"""Creates a ``Snooze`` that will prevent alerts, which match the + provided criteria, from being opened. The ``Snooze`` applies for + a specific time interval. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import monitoring_v3 + + def sample_create_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceClient() + + # Initialize request argument(s) + snooze = monitoring_v3.Snooze() + snooze.name = "name_value" + snooze.display_name = "display_name_value" + + request = monitoring_v3.CreateSnoozeRequest( + parent="parent_value", + snooze=snooze, + ) + + # Make the request + response = client.create_snooze(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.monitoring_v3.types.CreateSnoozeRequest, dict]): + The request object. The message definition for creating + a `Snooze`. Users must provide the body of the `Snooze` + to be created but must omit the `Snooze` field, `name`. + parent (str): + Required. The + `project `__ + in which a ``Snooze`` should be created. The format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER] + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + snooze (google.cloud.monitoring_v3.types.Snooze): + Required. The ``Snooze`` to create. Omit the ``name`` + field, as it will be filled in by the API. + + This corresponds to the ``snooze`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.monitoring_v3.types.Snooze: + A Snooze will prevent any alerts from being opened, and close any that + are already open. The Snooze will work on alerts that + match the criteria defined in the Snooze. The Snooze + will be active from interval.start_time through + interval.end_time. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, snooze]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a snooze_service.CreateSnoozeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, snooze_service.CreateSnoozeRequest): + request = snooze_service.CreateSnoozeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if snooze is not None: + request.snooze = snooze + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_snooze] + + # 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_snoozes( + self, + request: Optional[Union[snooze_service.ListSnoozesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSnoozesPager: + r"""Lists the ``Snooze``\ s associated with a project. Can + optionally pass in ``filter``, which specifies predicates to + match ``Snooze``\ s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import monitoring_v3 + + def sample_list_snoozes(): + # Create a client + client = monitoring_v3.SnoozeServiceClient() + + # Initialize request argument(s) + request = monitoring_v3.ListSnoozesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_snoozes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.monitoring_v3.types.ListSnoozesRequest, dict]): + The request object. The message definition for listing + `Snooze`s associated with the given `parent`, satisfying + the optional `filter`. + parent (str): + Required. The + `project `__ + whose ``Snooze``\ s should be listed. The format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER] + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.monitoring_v3.services.snooze_service.pagers.ListSnoozesPager: + The results of a successful ListSnoozes call, containing the matching + Snoozes. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a snooze_service.ListSnoozesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, snooze_service.ListSnoozesRequest): + request = snooze_service.ListSnoozesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_snoozes] + + # 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.ListSnoozesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_snooze( + self, + request: Optional[Union[snooze_service.GetSnoozeRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> snooze.Snooze: + r"""Retrieves a ``Snooze`` by ``name``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import monitoring_v3 + + def sample_get_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceClient() + + # Initialize request argument(s) + request = monitoring_v3.GetSnoozeRequest( + name="name_value", + ) + + # Make the request + response = client.get_snooze(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.monitoring_v3.types.GetSnoozeRequest, dict]): + The request object. The message definition for + retrieving a `Snooze`. Users must specify the field, + `name`, which identifies the `Snooze`. + name (str): + Required. The ID of the ``Snooze`` to retrieve. The + format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER]/snoozes/[SNOOZE_ID] + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.monitoring_v3.types.Snooze: + A Snooze will prevent any alerts from being opened, and close any that + are already open. The Snooze will work on alerts that + match the criteria defined in the Snooze. The Snooze + will be active from interval.start_time through + interval.end_time. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a snooze_service.GetSnoozeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, snooze_service.GetSnoozeRequest): + request = snooze_service.GetSnoozeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_snooze] + + # 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 update_snooze( + self, + request: Optional[Union[snooze_service.UpdateSnoozeRequest, dict]] = None, + *, + snooze: Optional[gm_snooze.Snooze] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gm_snooze.Snooze: + r"""Updates a ``Snooze``, identified by its ``name``, with the + parameters in the given ``Snooze`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import monitoring_v3 + + def sample_update_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceClient() + + # Initialize request argument(s) + snooze = monitoring_v3.Snooze() + snooze.name = "name_value" + snooze.display_name = "display_name_value" + + request = monitoring_v3.UpdateSnoozeRequest( + snooze=snooze, + ) + + # Make the request + response = client.update_snooze(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.monitoring_v3.types.UpdateSnoozeRequest, dict]): + The request object. The message definition for updating + a `Snooze`. The field, `snooze.name` identifies the + `Snooze` to be updated. The remainder of `snooze` gives + the content the `Snooze` in question will be assigned. + + What fields can be updated depends on the start time and + end time of the `Snooze`. + * end time is in the past: These `Snooze`s are + considered read-only and cannot be updated. + * start time is in the past and end time is in the + future: `display_name` and `interval.end_time` can + be updated. + * start time is in the future: `display_name`, + `interval.start_time` and `interval.end_time` can be + updated. + snooze (google.cloud.monitoring_v3.types.Snooze): + Required. The ``Snooze`` to update. Must have the name + field present. + + This corresponds to the ``snooze`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to update. + + For each field listed in ``update_mask``: + + - If the ``Snooze`` object supplied in the + ``UpdateSnoozeRequest`` has a value for that field, + the value of the field in the existing ``Snooze`` + will be set to the value of the field in the supplied + ``Snooze``. + - If the field does not have a value in the supplied + ``Snooze``, the field in the existing ``Snooze`` is + set to its default value. + + Fields not listed retain their existing value. + + The following are the field names that are accepted in + ``update_mask``: + + - ``display_name`` + - ``interval.start_time`` + - ``interval.end_time`` + + That said, the start time and end time of the ``Snooze`` + determines which fields can legally be updated. Before + attempting an update, users should consult the + documentation for ``UpdateSnoozeRequest``, which talks + about which fields can be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.monitoring_v3.types.Snooze: + A Snooze will prevent any alerts from being opened, and close any that + are already open. The Snooze will work on alerts that + match the criteria defined in the Snooze. The Snooze + will be active from interval.start_time through + interval.end_time. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([snooze, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a snooze_service.UpdateSnoozeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, snooze_service.UpdateSnoozeRequest): + request = snooze_service.UpdateSnoozeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if snooze is not None: + request.snooze = snooze + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_snooze] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("snooze.name", request.snooze.name),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("SnoozeServiceClient",) diff --git a/google/cloud/monitoring_v3/services/snooze_service/pagers.py b/google/cloud/monitoring_v3/services/snooze_service/pagers.py new file mode 100644 index 00000000..6dc25b15 --- /dev/null +++ b/google/cloud/monitoring_v3/services/snooze_service/pagers.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Sequence, + Tuple, + Optional, + Iterator, +) + +from google.cloud.monitoring_v3.types import snooze +from google.cloud.monitoring_v3.types import snooze_service + + +class ListSnoozesPager: + """A pager for iterating through ``list_snoozes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.monitoring_v3.types.ListSnoozesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``snoozes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSnoozes`` requests and continue to iterate + through the ``snoozes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.monitoring_v3.types.ListSnoozesResponse` + 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[..., snooze_service.ListSnoozesResponse], + request: snooze_service.ListSnoozesRequest, + response: snooze_service.ListSnoozesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.monitoring_v3.types.ListSnoozesRequest): + The initial request object. + response (google.cloud.monitoring_v3.types.ListSnoozesResponse): + 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 = snooze_service.ListSnoozesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[snooze_service.ListSnoozesResponse]: + 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) -> Iterator[snooze.Snooze]: + for page in self.pages: + yield from page.snoozes + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSnoozesAsyncPager: + """A pager for iterating through ``list_snoozes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.monitoring_v3.types.ListSnoozesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``snoozes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSnoozes`` requests and continue to iterate + through the ``snoozes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.monitoring_v3.types.ListSnoozesResponse` + 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[snooze_service.ListSnoozesResponse]], + request: snooze_service.ListSnoozesRequest, + response: snooze_service.ListSnoozesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.monitoring_v3.types.ListSnoozesRequest): + The initial request object. + response (google.cloud.monitoring_v3.types.ListSnoozesResponse): + 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 = snooze_service.ListSnoozesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[snooze_service.ListSnoozesResponse]: + 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) -> AsyncIterator[snooze.Snooze]: + async def async_generator(): + async for page in self.pages: + for response in page.snoozes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/monitoring_v3/services/snooze_service/transports/__init__.py b/google/cloud/monitoring_v3/services/snooze_service/transports/__init__.py new file mode 100644 index 00000000..41113c93 --- /dev/null +++ b/google/cloud/monitoring_v3/services/snooze_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SnoozeServiceTransport +from .grpc import SnoozeServiceGrpcTransport +from .grpc_asyncio import SnoozeServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SnoozeServiceTransport]] +_transport_registry["grpc"] = SnoozeServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SnoozeServiceGrpcAsyncIOTransport + +__all__ = ( + "SnoozeServiceTransport", + "SnoozeServiceGrpcTransport", + "SnoozeServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/monitoring_v3/services/snooze_service/transports/base.py b/google/cloud/monitoring_v3/services/snooze_service/transports/base.py new file mode 100644 index 00000000..827548b6 --- /dev/null +++ b/google/cloud/monitoring_v3/services/snooze_service/transports/base.py @@ -0,0 +1,225 @@ +# -*- 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 abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.monitoring_v3 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.monitoring_v3.types import snooze +from google.cloud.monitoring_v3.types import snooze as gm_snooze +from google.cloud.monitoring_v3.types import snooze_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class SnoozeServiceTransport(abc.ABC): + """Abstract transport class for SnoozeService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ) + + DEFAULT_HOST: str = "monitoring.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: 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. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_snooze: gapic_v1.method.wrap_method( + self.create_snooze, + default_timeout=30.0, + client_info=client_info, + ), + self.list_snoozes: gapic_v1.method.wrap_method( + self.list_snoozes, + default_retry=retries.Retry( + initial=0.1, + maximum=30.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_snooze: gapic_v1.method.wrap_method( + self.get_snooze, + default_retry=retries.Retry( + initial=0.1, + maximum=30.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.update_snooze: gapic_v1.method.wrap_method( + self.update_snooze, + default_timeout=30.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_snooze( + self, + ) -> Callable[ + [snooze_service.CreateSnoozeRequest], + Union[gm_snooze.Snooze, Awaitable[gm_snooze.Snooze]], + ]: + raise NotImplementedError() + + @property + def list_snoozes( + self, + ) -> Callable[ + [snooze_service.ListSnoozesRequest], + Union[ + snooze_service.ListSnoozesResponse, + Awaitable[snooze_service.ListSnoozesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_snooze( + self, + ) -> Callable[ + [snooze_service.GetSnoozeRequest], + Union[snooze.Snooze, Awaitable[snooze.Snooze]], + ]: + raise NotImplementedError() + + @property + def update_snooze( + self, + ) -> Callable[ + [snooze_service.UpdateSnoozeRequest], + Union[gm_snooze.Snooze, Awaitable[gm_snooze.Snooze]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SnoozeServiceTransport",) diff --git a/google/cloud/monitoring_v3/services/snooze_service/transports/grpc.py b/google/cloud/monitoring_v3/services/snooze_service/transports/grpc.py new file mode 100644 index 00000000..32f2a6a4 --- /dev/null +++ b/google/cloud/monitoring_v3/services/snooze_service/transports/grpc.py @@ -0,0 +1,354 @@ +# -*- 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 warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.monitoring_v3.types import snooze +from google.cloud.monitoring_v3.types import snooze as gm_snooze +from google.cloud.monitoring_v3.types import snooze_service +from .base import SnoozeServiceTransport, DEFAULT_CLIENT_INFO + + +class SnoozeServiceGrpcTransport(SnoozeServiceTransport): + """gRPC backend transport for SnoozeService. + + The SnoozeService API is used to temporarily prevent an alert + policy from generating alerts. A Snooze is a description of the + criteria under which one or more alert policies should not fire + alerts for the specified duration. + + 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[ga_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, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + 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]): Deprecated. 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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. 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. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "monitoring.googleapis.com", + credentials: Optional[ga_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. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_snooze( + self, + ) -> Callable[[snooze_service.CreateSnoozeRequest], gm_snooze.Snooze]: + r"""Return a callable for the create snooze method over gRPC. + + Creates a ``Snooze`` that will prevent alerts, which match the + provided criteria, from being opened. The ``Snooze`` applies for + a specific time interval. + + Returns: + Callable[[~.CreateSnoozeRequest], + ~.Snooze]: + 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_snooze" not in self._stubs: + self._stubs["create_snooze"] = self.grpc_channel.unary_unary( + "/google.monitoring.v3.SnoozeService/CreateSnooze", + request_serializer=snooze_service.CreateSnoozeRequest.serialize, + response_deserializer=gm_snooze.Snooze.deserialize, + ) + return self._stubs["create_snooze"] + + @property + def list_snoozes( + self, + ) -> Callable[ + [snooze_service.ListSnoozesRequest], snooze_service.ListSnoozesResponse + ]: + r"""Return a callable for the list snoozes method over gRPC. + + Lists the ``Snooze``\ s associated with a project. Can + optionally pass in ``filter``, which specifies predicates to + match ``Snooze``\ s. + + Returns: + Callable[[~.ListSnoozesRequest], + ~.ListSnoozesResponse]: + 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_snoozes" not in self._stubs: + self._stubs["list_snoozes"] = self.grpc_channel.unary_unary( + "/google.monitoring.v3.SnoozeService/ListSnoozes", + request_serializer=snooze_service.ListSnoozesRequest.serialize, + response_deserializer=snooze_service.ListSnoozesResponse.deserialize, + ) + return self._stubs["list_snoozes"] + + @property + def get_snooze(self) -> Callable[[snooze_service.GetSnoozeRequest], snooze.Snooze]: + r"""Return a callable for the get snooze method over gRPC. + + Retrieves a ``Snooze`` by ``name``. + + Returns: + Callable[[~.GetSnoozeRequest], + ~.Snooze]: + 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_snooze" not in self._stubs: + self._stubs["get_snooze"] = self.grpc_channel.unary_unary( + "/google.monitoring.v3.SnoozeService/GetSnooze", + request_serializer=snooze_service.GetSnoozeRequest.serialize, + response_deserializer=snooze.Snooze.deserialize, + ) + return self._stubs["get_snooze"] + + @property + def update_snooze( + self, + ) -> Callable[[snooze_service.UpdateSnoozeRequest], gm_snooze.Snooze]: + r"""Return a callable for the update snooze method over gRPC. + + Updates a ``Snooze``, identified by its ``name``, with the + parameters in the given ``Snooze`` object. + + Returns: + Callable[[~.UpdateSnoozeRequest], + ~.Snooze]: + 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_snooze" not in self._stubs: + self._stubs["update_snooze"] = self.grpc_channel.unary_unary( + "/google.monitoring.v3.SnoozeService/UpdateSnooze", + request_serializer=snooze_service.UpdateSnoozeRequest.serialize, + response_deserializer=gm_snooze.Snooze.deserialize, + ) + return self._stubs["update_snooze"] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SnoozeServiceGrpcTransport",) diff --git a/google/cloud/monitoring_v3/services/snooze_service/transports/grpc_asyncio.py b/google/cloud/monitoring_v3/services/snooze_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..9f8946fa --- /dev/null +++ b/google/cloud/monitoring_v3/services/snooze_service/transports/grpc_asyncio.py @@ -0,0 +1,356 @@ +# -*- 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 warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.monitoring_v3.types import snooze +from google.cloud.monitoring_v3.types import snooze as gm_snooze +from google.cloud.monitoring_v3.types import snooze_service +from .base import SnoozeServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SnoozeServiceGrpcTransport + + +class SnoozeServiceGrpcAsyncIOTransport(SnoozeServiceTransport): + """gRPC AsyncIO backend transport for SnoozeService. + + The SnoozeService API is used to temporarily prevent an alert + policy from generating alerts. A Snooze is a description of the + criteria under which one or more alert policies should not fire + alerts for the specified duration. + + 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[ga_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. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "monitoring.googleapis.com", + credentials: Optional[ga_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, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + 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]): Deprecated. 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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. 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. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @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. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_snooze( + self, + ) -> Callable[[snooze_service.CreateSnoozeRequest], Awaitable[gm_snooze.Snooze]]: + r"""Return a callable for the create snooze method over gRPC. + + Creates a ``Snooze`` that will prevent alerts, which match the + provided criteria, from being opened. The ``Snooze`` applies for + a specific time interval. + + Returns: + Callable[[~.CreateSnoozeRequest], + Awaitable[~.Snooze]]: + 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_snooze" not in self._stubs: + self._stubs["create_snooze"] = self.grpc_channel.unary_unary( + "/google.monitoring.v3.SnoozeService/CreateSnooze", + request_serializer=snooze_service.CreateSnoozeRequest.serialize, + response_deserializer=gm_snooze.Snooze.deserialize, + ) + return self._stubs["create_snooze"] + + @property + def list_snoozes( + self, + ) -> Callable[ + [snooze_service.ListSnoozesRequest], + Awaitable[snooze_service.ListSnoozesResponse], + ]: + r"""Return a callable for the list snoozes method over gRPC. + + Lists the ``Snooze``\ s associated with a project. Can + optionally pass in ``filter``, which specifies predicates to + match ``Snooze``\ s. + + Returns: + Callable[[~.ListSnoozesRequest], + Awaitable[~.ListSnoozesResponse]]: + 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_snoozes" not in self._stubs: + self._stubs["list_snoozes"] = self.grpc_channel.unary_unary( + "/google.monitoring.v3.SnoozeService/ListSnoozes", + request_serializer=snooze_service.ListSnoozesRequest.serialize, + response_deserializer=snooze_service.ListSnoozesResponse.deserialize, + ) + return self._stubs["list_snoozes"] + + @property + def get_snooze( + self, + ) -> Callable[[snooze_service.GetSnoozeRequest], Awaitable[snooze.Snooze]]: + r"""Return a callable for the get snooze method over gRPC. + + Retrieves a ``Snooze`` by ``name``. + + Returns: + Callable[[~.GetSnoozeRequest], + Awaitable[~.Snooze]]: + 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_snooze" not in self._stubs: + self._stubs["get_snooze"] = self.grpc_channel.unary_unary( + "/google.monitoring.v3.SnoozeService/GetSnooze", + request_serializer=snooze_service.GetSnoozeRequest.serialize, + response_deserializer=snooze.Snooze.deserialize, + ) + return self._stubs["get_snooze"] + + @property + def update_snooze( + self, + ) -> Callable[[snooze_service.UpdateSnoozeRequest], Awaitable[gm_snooze.Snooze]]: + r"""Return a callable for the update snooze method over gRPC. + + Updates a ``Snooze``, identified by its ``name``, with the + parameters in the given ``Snooze`` object. + + Returns: + Callable[[~.UpdateSnoozeRequest], + Awaitable[~.Snooze]]: + 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_snooze" not in self._stubs: + self._stubs["update_snooze"] = self.grpc_channel.unary_unary( + "/google.monitoring.v3.SnoozeService/UpdateSnooze", + request_serializer=snooze_service.UpdateSnoozeRequest.serialize, + response_deserializer=gm_snooze.Snooze.deserialize, + ) + return self._stubs["update_snooze"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("SnoozeServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/monitoring_v3/types/__init__.py b/google/cloud/monitoring_v3/types/__init__.py index 27ed04a1..c9524827 100644 --- a/google/cloud/monitoring_v3/types/__init__.py +++ b/google/cloud/monitoring_v3/types/__init__.py @@ -121,6 +121,16 @@ UpdateServiceLevelObjectiveRequest, UpdateServiceRequest, ) +from .snooze import ( + Snooze, +) +from .snooze_service import ( + CreateSnoozeRequest, + GetSnoozeRequest, + ListSnoozesRequest, + ListSnoozesResponse, + UpdateSnoozeRequest, +) from .span_context import ( SpanContext, ) @@ -225,6 +235,12 @@ "ListServicesResponse", "UpdateServiceLevelObjectiveRequest", "UpdateServiceRequest", + "Snooze", + "CreateSnoozeRequest", + "GetSnoozeRequest", + "ListSnoozesRequest", + "ListSnoozesResponse", + "UpdateSnoozeRequest", "SpanContext", "InternalChecker", "UptimeCheckConfig", diff --git a/google/cloud/monitoring_v3/types/snooze.py b/google/cloud/monitoring_v3/types/snooze.py new file mode 100644 index 00000000..eb5fd012 --- /dev/null +++ b/google/cloud/monitoring_v3/types/snooze.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.monitoring_v3.types import common + + +__protobuf__ = proto.module( + package="google.monitoring.v3", + manifest={ + "Snooze", + }, +) + + +class Snooze(proto.Message): + r"""A ``Snooze`` will prevent any alerts from being opened, and close + any that are already open. The ``Snooze`` will work on alerts that + match the criteria defined in the ``Snooze``. The ``Snooze`` will be + active from ``interval.start_time`` through ``interval.end_time``. + + Attributes: + name (str): + Required. The name of the ``Snooze``. The format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER]/snoozes/[SNOOZE_ID] + + The ID of the ``Snooze`` will be generated by the system. + criteria (google.cloud.monitoring_v3.types.Snooze.Criteria): + Required. This defines the criteria for applying the + ``Snooze``. See ``Criteria`` for more information. + interval (google.cloud.monitoring_v3.types.TimeInterval): + Required. The ``Snooze`` will be active from + ``interval.start_time`` through ``interval.end_time``. + ``interval.start_time`` cannot be in the past. There is a 15 + second clock skew to account for the time it takes for a + request to reach the API from the UI. + display_name (str): + Required. A display name for the ``Snooze``. This can be, at + most, 512 unicode characters. + """ + + class Criteria(proto.Message): + r"""Criteria specific to the ``AlertPolicy``\ s that this ``Snooze`` + applies to. The ``Snooze`` will suppress alerts that come from one + of the ``AlertPolicy``\ s whose names are supplied. + + Attributes: + policies (MutableSequence[str]): + The specific ``AlertPolicy`` names for the alert that should + be snoozed. The format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[POLICY_ID] + + There is a limit of 10 policies per snooze. This limit is + checked during snooze creation. + """ + + policies: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + criteria: Criteria = proto.Field( + proto.MESSAGE, + number=3, + message=Criteria, + ) + interval: common.TimeInterval = proto.Field( + proto.MESSAGE, + number=4, + message=common.TimeInterval, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/snooze_service.py b/google/cloud/monitoring_v3/types/snooze_service.py new file mode 100644 index 00000000..be0cc021 --- /dev/null +++ b/google/cloud/monitoring_v3/types/snooze_service.py @@ -0,0 +1,233 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.monitoring_v3.types import snooze as gm_snooze +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.monitoring.v3", + manifest={ + "CreateSnoozeRequest", + "ListSnoozesRequest", + "ListSnoozesResponse", + "GetSnoozeRequest", + "UpdateSnoozeRequest", + }, +) + + +class CreateSnoozeRequest(proto.Message): + r"""The message definition for creating a ``Snooze``. Users must provide + the body of the ``Snooze`` to be created but must omit the + ``Snooze`` field, ``name``. + + Attributes: + parent (str): + Required. The + `project `__ + in which a ``Snooze`` should be created. The format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER] + snooze (google.cloud.monitoring_v3.types.Snooze): + Required. The ``Snooze`` to create. Omit the ``name`` field, + as it will be filled in by the API. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + snooze: gm_snooze.Snooze = proto.Field( + proto.MESSAGE, + number=2, + message=gm_snooze.Snooze, + ) + + +class ListSnoozesRequest(proto.Message): + r"""The message definition for listing ``Snooze``\ s associated with the + given ``parent``, satisfying the optional ``filter``. + + Attributes: + parent (str): + Required. The + `project `__ + whose ``Snooze``\ s should be listed. The format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER] + filter (str): + Optional. Optional filter to restrict results to the given + criteria. The following fields are supported. + + - ``interval.start_time`` + - ``interval.end_time`` + + For example: + + :: + + ``` + interval.start_time > "2022-03-11T00:00:00-08:00" AND + interval.end_time < "2022-03-12T00:00:00-08:00" + ``` + page_size (int): + Optional. The maximum number of results to return for a + single query. The server may further constrain the maximum + number of results returned in a single page. The value + should be in the range [1, 1000]. If the value given is + outside this range, the server will decide the number of + results to be returned. + page_token (str): + Optional. The ``next_page_token`` from a previous call to + ``ListSnoozesRequest`` to get the next page of results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListSnoozesResponse(proto.Message): + r"""The results of a successful ``ListSnoozes`` call, containing the + matching ``Snooze``\ s. + + Attributes: + snoozes (MutableSequence[google.cloud.monitoring_v3.types.Snooze]): + ``Snooze``\ s matching this list call. + next_page_token (str): + Page token for repeated calls to ``ListSnoozes``, to fetch + additional pages of results. If this is empty or missing, + there are no more pages. + """ + + @property + def raw_page(self): + return self + + snoozes: MutableSequence[gm_snooze.Snooze] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gm_snooze.Snooze, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSnoozeRequest(proto.Message): + r"""The message definition for retrieving a ``Snooze``. Users must + specify the field, ``name``, which identifies the ``Snooze``. + + Attributes: + name (str): + Required. The ID of the ``Snooze`` to retrieve. The format + is: + + :: + + projects/[PROJECT_ID_OR_NUMBER]/snoozes/[SNOOZE_ID] + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSnoozeRequest(proto.Message): + r"""The message definition for updating a ``Snooze``. The field, + ``snooze.name`` identifies the ``Snooze`` to be updated. The + remainder of ``snooze`` gives the content the ``Snooze`` in question + will be assigned. + + What fields can be updated depends on the start time and end time of + the ``Snooze``. + + - end time is in the past: These ``Snooze``\ s are considered + read-only and cannot be updated. + - start time is in the past and end time is in the future: + ``display_name`` and ``interval.end_time`` can be updated. + - start time is in the future: ``display_name``, + ``interval.start_time`` and ``interval.end_time`` can be updated. + + Attributes: + snooze (google.cloud.monitoring_v3.types.Snooze): + Required. The ``Snooze`` to update. Must have the name field + present. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to update. + + For each field listed in ``update_mask``: + + - If the ``Snooze`` object supplied in the + ``UpdateSnoozeRequest`` has a value for that field, the + value of the field in the existing ``Snooze`` will be set + to the value of the field in the supplied ``Snooze``. + - If the field does not have a value in the supplied + ``Snooze``, the field in the existing ``Snooze`` is set + to its default value. + + Fields not listed retain their existing value. + + The following are the field names that are accepted in + ``update_mask``: + + - ``display_name`` + - ``interval.start_time`` + - ``interval.end_time`` + + That said, the start time and end time of the ``Snooze`` + determines which fields can legally be updated. Before + attempting an update, users should consult the documentation + for ``UpdateSnoozeRequest``, which talks about which fields + can be updated. + """ + + snooze: gm_snooze.Snooze = proto.Field( + proto.MESSAGE, + number=1, + message=gm_snooze.Snooze, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/samples/generated_samples/monitoring_v3_generated_snooze_service_create_snooze_async.py b/samples/generated_samples/monitoring_v3_generated_snooze_service_create_snooze_async.py new file mode 100644 index 00000000..7b1564d1 --- /dev/null +++ b/samples/generated_samples/monitoring_v3_generated_snooze_service_create_snooze_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSnooze +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-monitoring + + +# [START monitoring_v3_generated_SnoozeService_CreateSnooze_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import monitoring_v3 + + +async def sample_create_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceAsyncClient() + + # Initialize request argument(s) + snooze = monitoring_v3.Snooze() + snooze.name = "name_value" + snooze.display_name = "display_name_value" + + request = monitoring_v3.CreateSnoozeRequest( + parent="parent_value", + snooze=snooze, + ) + + # Make the request + response = await client.create_snooze(request=request) + + # Handle the response + print(response) + +# [END monitoring_v3_generated_SnoozeService_CreateSnooze_async] diff --git a/samples/generated_samples/monitoring_v3_generated_snooze_service_create_snooze_sync.py b/samples/generated_samples/monitoring_v3_generated_snooze_service_create_snooze_sync.py new file mode 100644 index 00000000..8f364237 --- /dev/null +++ b/samples/generated_samples/monitoring_v3_generated_snooze_service_create_snooze_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSnooze +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-monitoring + + +# [START monitoring_v3_generated_SnoozeService_CreateSnooze_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import monitoring_v3 + + +def sample_create_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceClient() + + # Initialize request argument(s) + snooze = monitoring_v3.Snooze() + snooze.name = "name_value" + snooze.display_name = "display_name_value" + + request = monitoring_v3.CreateSnoozeRequest( + parent="parent_value", + snooze=snooze, + ) + + # Make the request + response = client.create_snooze(request=request) + + # Handle the response + print(response) + +# [END monitoring_v3_generated_SnoozeService_CreateSnooze_sync] diff --git a/samples/generated_samples/monitoring_v3_generated_snooze_service_get_snooze_async.py b/samples/generated_samples/monitoring_v3_generated_snooze_service_get_snooze_async.py new file mode 100644 index 00000000..80ac6c8f --- /dev/null +++ b/samples/generated_samples/monitoring_v3_generated_snooze_service_get_snooze_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSnooze +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-monitoring + + +# [START monitoring_v3_generated_SnoozeService_GetSnooze_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import monitoring_v3 + + +async def sample_get_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceAsyncClient() + + # Initialize request argument(s) + request = monitoring_v3.GetSnoozeRequest( + name="name_value", + ) + + # Make the request + response = await client.get_snooze(request=request) + + # Handle the response + print(response) + +# [END monitoring_v3_generated_SnoozeService_GetSnooze_async] diff --git a/samples/generated_samples/monitoring_v3_generated_snooze_service_get_snooze_sync.py b/samples/generated_samples/monitoring_v3_generated_snooze_service_get_snooze_sync.py new file mode 100644 index 00000000..bd8bb388 --- /dev/null +++ b/samples/generated_samples/monitoring_v3_generated_snooze_service_get_snooze_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSnooze +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-monitoring + + +# [START monitoring_v3_generated_SnoozeService_GetSnooze_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import monitoring_v3 + + +def sample_get_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceClient() + + # Initialize request argument(s) + request = monitoring_v3.GetSnoozeRequest( + name="name_value", + ) + + # Make the request + response = client.get_snooze(request=request) + + # Handle the response + print(response) + +# [END monitoring_v3_generated_SnoozeService_GetSnooze_sync] diff --git a/samples/generated_samples/monitoring_v3_generated_snooze_service_list_snoozes_async.py b/samples/generated_samples/monitoring_v3_generated_snooze_service_list_snoozes_async.py new file mode 100644 index 00000000..b7e78eaf --- /dev/null +++ b/samples/generated_samples/monitoring_v3_generated_snooze_service_list_snoozes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSnoozes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-monitoring + + +# [START monitoring_v3_generated_SnoozeService_ListSnoozes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import monitoring_v3 + + +async def sample_list_snoozes(): + # Create a client + client = monitoring_v3.SnoozeServiceAsyncClient() + + # Initialize request argument(s) + request = monitoring_v3.ListSnoozesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_snoozes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END monitoring_v3_generated_SnoozeService_ListSnoozes_async] diff --git a/samples/generated_samples/monitoring_v3_generated_snooze_service_list_snoozes_sync.py b/samples/generated_samples/monitoring_v3_generated_snooze_service_list_snoozes_sync.py new file mode 100644 index 00000000..bb6c504a --- /dev/null +++ b/samples/generated_samples/monitoring_v3_generated_snooze_service_list_snoozes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSnoozes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-monitoring + + +# [START monitoring_v3_generated_SnoozeService_ListSnoozes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import monitoring_v3 + + +def sample_list_snoozes(): + # Create a client + client = monitoring_v3.SnoozeServiceClient() + + # Initialize request argument(s) + request = monitoring_v3.ListSnoozesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_snoozes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END monitoring_v3_generated_SnoozeService_ListSnoozes_sync] diff --git a/samples/generated_samples/monitoring_v3_generated_snooze_service_update_snooze_async.py b/samples/generated_samples/monitoring_v3_generated_snooze_service_update_snooze_async.py new file mode 100644 index 00000000..37c43908 --- /dev/null +++ b/samples/generated_samples/monitoring_v3_generated_snooze_service_update_snooze_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSnooze +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-monitoring + + +# [START monitoring_v3_generated_SnoozeService_UpdateSnooze_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import monitoring_v3 + + +async def sample_update_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceAsyncClient() + + # Initialize request argument(s) + snooze = monitoring_v3.Snooze() + snooze.name = "name_value" + snooze.display_name = "display_name_value" + + request = monitoring_v3.UpdateSnoozeRequest( + snooze=snooze, + ) + + # Make the request + response = await client.update_snooze(request=request) + + # Handle the response + print(response) + +# [END monitoring_v3_generated_SnoozeService_UpdateSnooze_async] diff --git a/samples/generated_samples/monitoring_v3_generated_snooze_service_update_snooze_sync.py b/samples/generated_samples/monitoring_v3_generated_snooze_service_update_snooze_sync.py new file mode 100644 index 00000000..154c2915 --- /dev/null +++ b/samples/generated_samples/monitoring_v3_generated_snooze_service_update_snooze_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSnooze +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-monitoring + + +# [START monitoring_v3_generated_SnoozeService_UpdateSnooze_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import monitoring_v3 + + +def sample_update_snooze(): + # Create a client + client = monitoring_v3.SnoozeServiceClient() + + # Initialize request argument(s) + snooze = monitoring_v3.Snooze() + snooze.name = "name_value" + snooze.display_name = "display_name_value" + + request = monitoring_v3.UpdateSnoozeRequest( + snooze=snooze, + ) + + # Make the request + response = client.update_snooze(request=request) + + # Handle the response + print(response) + +# [END monitoring_v3_generated_SnoozeService_UpdateSnooze_sync] diff --git a/samples/generated_samples/snippet_metadata_google.monitoring.v3.json b/samples/generated_samples/snippet_metadata_google.monitoring.v3.json index e3ab6eeb..04888a5f 100644 --- a/samples/generated_samples/snippet_metadata_google.monitoring.v3.json +++ b/samples/generated_samples/snippet_metadata_google.monitoring.v3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-monitoring", - "version": "2.12.0" + "version": "0.1.0" }, "snippets": [ { @@ -6670,6 +6670,666 @@ ], "title": "monitoring_v3_generated_service_monitoring_service_update_service_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.monitoring_v3.SnoozeServiceAsyncClient", + "shortName": "SnoozeServiceAsyncClient" + }, + "fullName": "google.cloud.monitoring_v3.SnoozeServiceAsyncClient.create_snooze", + "method": { + "fullName": "google.monitoring.v3.SnoozeService.CreateSnooze", + "service": { + "fullName": "google.monitoring.v3.SnoozeService", + "shortName": "SnoozeService" + }, + "shortName": "CreateSnooze" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.monitoring_v3.types.CreateSnoozeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "snooze", + "type": "google.cloud.monitoring_v3.types.Snooze" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.monitoring_v3.types.Snooze", + "shortName": "create_snooze" + }, + "description": "Sample for CreateSnooze", + "file": "monitoring_v3_generated_snooze_service_create_snooze_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "monitoring_v3_generated_SnoozeService_CreateSnooze_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "monitoring_v3_generated_snooze_service_create_snooze_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.monitoring_v3.SnoozeServiceClient", + "shortName": "SnoozeServiceClient" + }, + "fullName": "google.cloud.monitoring_v3.SnoozeServiceClient.create_snooze", + "method": { + "fullName": "google.monitoring.v3.SnoozeService.CreateSnooze", + "service": { + "fullName": "google.monitoring.v3.SnoozeService", + "shortName": "SnoozeService" + }, + "shortName": "CreateSnooze" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.monitoring_v3.types.CreateSnoozeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "snooze", + "type": "google.cloud.monitoring_v3.types.Snooze" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.monitoring_v3.types.Snooze", + "shortName": "create_snooze" + }, + "description": "Sample for CreateSnooze", + "file": "monitoring_v3_generated_snooze_service_create_snooze_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "monitoring_v3_generated_SnoozeService_CreateSnooze_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "monitoring_v3_generated_snooze_service_create_snooze_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.monitoring_v3.SnoozeServiceAsyncClient", + "shortName": "SnoozeServiceAsyncClient" + }, + "fullName": "google.cloud.monitoring_v3.SnoozeServiceAsyncClient.get_snooze", + "method": { + "fullName": "google.monitoring.v3.SnoozeService.GetSnooze", + "service": { + "fullName": "google.monitoring.v3.SnoozeService", + "shortName": "SnoozeService" + }, + "shortName": "GetSnooze" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.monitoring_v3.types.GetSnoozeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.monitoring_v3.types.Snooze", + "shortName": "get_snooze" + }, + "description": "Sample for GetSnooze", + "file": "monitoring_v3_generated_snooze_service_get_snooze_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "monitoring_v3_generated_SnoozeService_GetSnooze_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "monitoring_v3_generated_snooze_service_get_snooze_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.monitoring_v3.SnoozeServiceClient", + "shortName": "SnoozeServiceClient" + }, + "fullName": "google.cloud.monitoring_v3.SnoozeServiceClient.get_snooze", + "method": { + "fullName": "google.monitoring.v3.SnoozeService.GetSnooze", + "service": { + "fullName": "google.monitoring.v3.SnoozeService", + "shortName": "SnoozeService" + }, + "shortName": "GetSnooze" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.monitoring_v3.types.GetSnoozeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.monitoring_v3.types.Snooze", + "shortName": "get_snooze" + }, + "description": "Sample for GetSnooze", + "file": "monitoring_v3_generated_snooze_service_get_snooze_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "monitoring_v3_generated_SnoozeService_GetSnooze_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "monitoring_v3_generated_snooze_service_get_snooze_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.monitoring_v3.SnoozeServiceAsyncClient", + "shortName": "SnoozeServiceAsyncClient" + }, + "fullName": "google.cloud.monitoring_v3.SnoozeServiceAsyncClient.list_snoozes", + "method": { + "fullName": "google.monitoring.v3.SnoozeService.ListSnoozes", + "service": { + "fullName": "google.monitoring.v3.SnoozeService", + "shortName": "SnoozeService" + }, + "shortName": "ListSnoozes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.monitoring_v3.types.ListSnoozesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.monitoring_v3.services.snooze_service.pagers.ListSnoozesAsyncPager", + "shortName": "list_snoozes" + }, + "description": "Sample for ListSnoozes", + "file": "monitoring_v3_generated_snooze_service_list_snoozes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "monitoring_v3_generated_SnoozeService_ListSnoozes_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "monitoring_v3_generated_snooze_service_list_snoozes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.monitoring_v3.SnoozeServiceClient", + "shortName": "SnoozeServiceClient" + }, + "fullName": "google.cloud.monitoring_v3.SnoozeServiceClient.list_snoozes", + "method": { + "fullName": "google.monitoring.v3.SnoozeService.ListSnoozes", + "service": { + "fullName": "google.monitoring.v3.SnoozeService", + "shortName": "SnoozeService" + }, + "shortName": "ListSnoozes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.monitoring_v3.types.ListSnoozesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.monitoring_v3.services.snooze_service.pagers.ListSnoozesPager", + "shortName": "list_snoozes" + }, + "description": "Sample for ListSnoozes", + "file": "monitoring_v3_generated_snooze_service_list_snoozes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "monitoring_v3_generated_SnoozeService_ListSnoozes_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "monitoring_v3_generated_snooze_service_list_snoozes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.monitoring_v3.SnoozeServiceAsyncClient", + "shortName": "SnoozeServiceAsyncClient" + }, + "fullName": "google.cloud.monitoring_v3.SnoozeServiceAsyncClient.update_snooze", + "method": { + "fullName": "google.monitoring.v3.SnoozeService.UpdateSnooze", + "service": { + "fullName": "google.monitoring.v3.SnoozeService", + "shortName": "SnoozeService" + }, + "shortName": "UpdateSnooze" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.monitoring_v3.types.UpdateSnoozeRequest" + }, + { + "name": "snooze", + "type": "google.cloud.monitoring_v3.types.Snooze" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.monitoring_v3.types.Snooze", + "shortName": "update_snooze" + }, + "description": "Sample for UpdateSnooze", + "file": "monitoring_v3_generated_snooze_service_update_snooze_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "monitoring_v3_generated_SnoozeService_UpdateSnooze_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "monitoring_v3_generated_snooze_service_update_snooze_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.monitoring_v3.SnoozeServiceClient", + "shortName": "SnoozeServiceClient" + }, + "fullName": "google.cloud.monitoring_v3.SnoozeServiceClient.update_snooze", + "method": { + "fullName": "google.monitoring.v3.SnoozeService.UpdateSnooze", + "service": { + "fullName": "google.monitoring.v3.SnoozeService", + "shortName": "SnoozeService" + }, + "shortName": "UpdateSnooze" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.monitoring_v3.types.UpdateSnoozeRequest" + }, + { + "name": "snooze", + "type": "google.cloud.monitoring_v3.types.Snooze" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.monitoring_v3.types.Snooze", + "shortName": "update_snooze" + }, + "description": "Sample for UpdateSnooze", + "file": "monitoring_v3_generated_snooze_service_update_snooze_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "monitoring_v3_generated_SnoozeService_UpdateSnooze_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "monitoring_v3_generated_snooze_service_update_snooze_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/scripts/fixup_monitoring_v3_keywords.py b/scripts/fixup_monitoring_v3_keywords.py index 86f15e0c..1d1040c4 100644 --- a/scripts/fixup_monitoring_v3_keywords.py +++ b/scripts/fixup_monitoring_v3_keywords.py @@ -46,6 +46,7 @@ class monitoringCallTransformer(cst.CSTTransformer): 'create_service': ('parent', 'service', 'service_id', ), 'create_service_level_objective': ('parent', 'service_level_objective', 'service_level_objective_id', ), 'create_service_time_series': ('name', 'time_series', ), + 'create_snooze': ('parent', 'snooze', ), 'create_time_series': ('name', 'time_series', ), 'create_uptime_check_config': ('parent', 'uptime_check_config', ), 'delete_alert_policy': ('name', ), @@ -64,6 +65,7 @@ class monitoringCallTransformer(cst.CSTTransformer): 'get_notification_channel_verification_code': ('name', 'expire_time', ), 'get_service': ('name', ), 'get_service_level_objective': ('name', 'view', ), + 'get_snooze': ('name', ), 'get_uptime_check_config': ('name', ), 'list_alert_policies': ('name', 'filter', 'order_by', 'page_size', 'page_token', ), 'list_group_members': ('name', 'page_size', 'page_token', 'filter', 'interval', ), @@ -74,6 +76,7 @@ class monitoringCallTransformer(cst.CSTTransformer): 'list_notification_channels': ('name', 'filter', 'order_by', 'page_size', 'page_token', ), 'list_service_level_objectives': ('parent', 'filter', 'page_size', 'page_token', 'view', ), 'list_services': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_snoozes': ('parent', 'filter', 'page_size', 'page_token', ), 'list_time_series': ('name', 'filter', 'interval', 'view', 'aggregation', 'secondary_aggregation', 'order_by', 'page_size', 'page_token', ), 'list_uptime_check_configs': ('parent', 'page_size', 'page_token', ), 'list_uptime_check_ips': ('page_size', 'page_token', ), @@ -84,6 +87,7 @@ class monitoringCallTransformer(cst.CSTTransformer): 'update_notification_channel': ('notification_channel', 'update_mask', ), 'update_service': ('service', 'update_mask', ), 'update_service_level_objective': ('service_level_objective', 'update_mask', ), + 'update_snooze': ('snooze', 'update_mask', ), 'update_uptime_check_config': ('uptime_check_config', 'update_mask', ), 'verify_notification_channel': ('name', 'code', ), } diff --git a/tests/unit/gapic/monitoring_v3/test_snooze_service.py b/tests/unit/gapic/monitoring_v3/test_snooze_service.py new file mode 100644 index 00000000..87402d2b --- /dev/null +++ b/tests/unit/gapic/monitoring_v3/test_snooze_service.py @@ -0,0 +1,2575 @@ +# -*- 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 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 grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.monitoring_v3.services.snooze_service import SnoozeServiceAsyncClient +from google.cloud.monitoring_v3.services.snooze_service import SnoozeServiceClient +from google.cloud.monitoring_v3.services.snooze_service import pagers +from google.cloud.monitoring_v3.services.snooze_service import transports +from google.cloud.monitoring_v3.types import common +from google.cloud.monitoring_v3.types import snooze +from google.cloud.monitoring_v3.types import snooze as gm_snooze +from google.cloud.monitoring_v3.types import snooze_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +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 SnoozeServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SnoozeServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SnoozeServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SnoozeServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SnoozeServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SnoozeServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SnoozeServiceClient, "grpc"), + (SnoozeServiceAsyncClient, "grpc_asyncio"), + ], +) +def test_snooze_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.SnoozeServiceGrpcTransport, "grpc"), + (transports.SnoozeServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_snooze_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", + [ + (SnoozeServiceClient, "grpc"), + (SnoozeServiceAsyncClient, "grpc_asyncio"), + ], +) +def test_snooze_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_snooze_service_client_get_transport_class(): + transport = SnoozeServiceClient.get_transport_class() + available_transports = [ + transports.SnoozeServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SnoozeServiceClient.get_transport_class("grpc") + assert transport == transports.SnoozeServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SnoozeServiceClient, transports.SnoozeServiceGrpcTransport, "grpc"), + ( + SnoozeServiceAsyncClient, + transports.SnoozeServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + SnoozeServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SnoozeServiceClient), +) +@mock.patch.object( + SnoozeServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SnoozeServiceAsyncClient), +) +def test_snooze_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(SnoozeServiceClient, "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(SnoozeServiceClient, "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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + 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", + [ + (SnoozeServiceClient, transports.SnoozeServiceGrpcTransport, "grpc", "true"), + ( + SnoozeServiceAsyncClient, + transports.SnoozeServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (SnoozeServiceClient, transports.SnoozeServiceGrpcTransport, "grpc", "false"), + ( + SnoozeServiceAsyncClient, + transports.SnoozeServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + SnoozeServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SnoozeServiceClient), +) +@mock.patch.object( + SnoozeServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SnoozeServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_snooze_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", [SnoozeServiceClient, SnoozeServiceAsyncClient] +) +@mock.patch.object( + SnoozeServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SnoozeServiceClient), +) +@mock.patch.object( + SnoozeServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SnoozeServiceAsyncClient), +) +def test_snooze_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", + [ + (SnoozeServiceClient, transports.SnoozeServiceGrpcTransport, "grpc"), + ( + SnoozeServiceAsyncClient, + transports.SnoozeServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_snooze_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", + [ + ( + SnoozeServiceClient, + transports.SnoozeServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SnoozeServiceAsyncClient, + transports.SnoozeServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_snooze_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_snooze_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.monitoring_v3.services.snooze_service.transports.SnoozeServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SnoozeServiceClient( + 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", + [ + ( + SnoozeServiceClient, + transports.SnoozeServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SnoozeServiceAsyncClient, + transports.SnoozeServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_snooze_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", + ), + 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", + [ + snooze_service.CreateSnoozeRequest, + dict, + ], +) +def test_create_snooze(request_type, transport: str = "grpc"): + client = SnoozeServiceClient( + 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_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gm_snooze.Snooze( + name="name_value", + display_name="display_name_value", + ) + response = client.create_snooze(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.CreateSnoozeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gm_snooze.Snooze) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +def test_create_snooze_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 = SnoozeServiceClient( + 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_snooze), "__call__") as call: + client.create_snooze() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.CreateSnoozeRequest() + + +@pytest.mark.asyncio +async def test_create_snooze_async( + transport: str = "grpc_asyncio", request_type=snooze_service.CreateSnoozeRequest +): + client = SnoozeServiceAsyncClient( + 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_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gm_snooze.Snooze( + name="name_value", + display_name="display_name_value", + ) + ) + response = await client.create_snooze(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.CreateSnoozeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gm_snooze.Snooze) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_create_snooze_async_from_dict(): + await test_create_snooze_async(request_type=dict) + + +def test_create_snooze_field_headers(): + client = SnoozeServiceClient( + 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 = snooze_service.CreateSnoozeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_snooze), "__call__") as call: + call.return_value = gm_snooze.Snooze() + client.create_snooze(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_snooze_field_headers_async(): + client = SnoozeServiceAsyncClient( + 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 = snooze_service.CreateSnoozeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_snooze), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gm_snooze.Snooze()) + await client.create_snooze(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_create_snooze_flattened(): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gm_snooze.Snooze() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_snooze( + parent="parent_value", + snooze=gm_snooze.Snooze(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].snooze + mock_val = gm_snooze.Snooze(name="name_value") + assert arg == mock_val + + +def test_create_snooze_flattened_error(): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_snooze( + snooze_service.CreateSnoozeRequest(), + parent="parent_value", + snooze=gm_snooze.Snooze(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_snooze_flattened_async(): + client = SnoozeServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gm_snooze.Snooze() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gm_snooze.Snooze()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_snooze( + parent="parent_value", + snooze=gm_snooze.Snooze(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].snooze + mock_val = gm_snooze.Snooze(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_snooze_flattened_error_async(): + client = SnoozeServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_snooze( + snooze_service.CreateSnoozeRequest(), + parent="parent_value", + snooze=gm_snooze.Snooze(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + snooze_service.ListSnoozesRequest, + dict, + ], +) +def test_list_snoozes(request_type, transport: str = "grpc"): + client = SnoozeServiceClient( + 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_snoozes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = snooze_service.ListSnoozesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_snoozes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.ListSnoozesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSnoozesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_snoozes_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 = SnoozeServiceClient( + 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_snoozes), "__call__") as call: + client.list_snoozes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.ListSnoozesRequest() + + +@pytest.mark.asyncio +async def test_list_snoozes_async( + transport: str = "grpc_asyncio", request_type=snooze_service.ListSnoozesRequest +): + client = SnoozeServiceAsyncClient( + 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_snoozes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + snooze_service.ListSnoozesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_snoozes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.ListSnoozesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSnoozesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_snoozes_async_from_dict(): + await test_list_snoozes_async(request_type=dict) + + +def test_list_snoozes_field_headers(): + client = SnoozeServiceClient( + 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 = snooze_service.ListSnoozesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_snoozes), "__call__") as call: + call.return_value = snooze_service.ListSnoozesResponse() + client.list_snoozes(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_snoozes_field_headers_async(): + client = SnoozeServiceAsyncClient( + 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 = snooze_service.ListSnoozesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_snoozes), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + snooze_service.ListSnoozesResponse() + ) + await client.list_snoozes(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_snoozes_flattened(): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_snoozes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = snooze_service.ListSnoozesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_snoozes( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_snoozes_flattened_error(): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_snoozes( + snooze_service.ListSnoozesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_snoozes_flattened_async(): + client = SnoozeServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_snoozes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = snooze_service.ListSnoozesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + snooze_service.ListSnoozesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_snoozes( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_snoozes_flattened_error_async(): + client = SnoozeServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_snoozes( + snooze_service.ListSnoozesRequest(), + parent="parent_value", + ) + + +def test_list_snoozes_pager(transport_name: str = "grpc"): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_snoozes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + snooze.Snooze(), + snooze.Snooze(), + ], + next_page_token="abc", + ), + snooze_service.ListSnoozesResponse( + snoozes=[], + next_page_token="def", + ), + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + ], + next_page_token="ghi", + ), + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + snooze.Snooze(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_snoozes(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, snooze.Snooze) for i in results) + + +def test_list_snoozes_pages(transport_name: str = "grpc"): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_snoozes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + snooze.Snooze(), + snooze.Snooze(), + ], + next_page_token="abc", + ), + snooze_service.ListSnoozesResponse( + snoozes=[], + next_page_token="def", + ), + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + ], + next_page_token="ghi", + ), + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + snooze.Snooze(), + ], + ), + RuntimeError, + ) + pages = list(client.list_snoozes(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_snoozes_async_pager(): + client = SnoozeServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snoozes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + snooze.Snooze(), + snooze.Snooze(), + ], + next_page_token="abc", + ), + snooze_service.ListSnoozesResponse( + snoozes=[], + next_page_token="def", + ), + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + ], + next_page_token="ghi", + ), + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + snooze.Snooze(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_snoozes( + 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, snooze.Snooze) for i in responses) + + +@pytest.mark.asyncio +async def test_list_snoozes_async_pages(): + client = SnoozeServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snoozes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + snooze.Snooze(), + snooze.Snooze(), + ], + next_page_token="abc", + ), + snooze_service.ListSnoozesResponse( + snoozes=[], + next_page_token="def", + ), + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + ], + next_page_token="ghi", + ), + snooze_service.ListSnoozesResponse( + snoozes=[ + snooze.Snooze(), + snooze.Snooze(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_snoozes(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", + [ + snooze_service.GetSnoozeRequest, + dict, + ], +) +def test_get_snooze(request_type, transport: str = "grpc"): + client = SnoozeServiceClient( + 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_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = snooze.Snooze( + name="name_value", + display_name="display_name_value", + ) + response = client.get_snooze(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.GetSnoozeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, snooze.Snooze) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +def test_get_snooze_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 = SnoozeServiceClient( + 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_snooze), "__call__") as call: + client.get_snooze() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.GetSnoozeRequest() + + +@pytest.mark.asyncio +async def test_get_snooze_async( + transport: str = "grpc_asyncio", request_type=snooze_service.GetSnoozeRequest +): + client = SnoozeServiceAsyncClient( + 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_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + snooze.Snooze( + name="name_value", + display_name="display_name_value", + ) + ) + response = await client.get_snooze(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.GetSnoozeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, snooze.Snooze) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_get_snooze_async_from_dict(): + await test_get_snooze_async(request_type=dict) + + +def test_get_snooze_field_headers(): + client = SnoozeServiceClient( + 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 = snooze_service.GetSnoozeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_snooze), "__call__") as call: + call.return_value = snooze.Snooze() + client.get_snooze(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_snooze_field_headers_async(): + client = SnoozeServiceAsyncClient( + 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 = snooze_service.GetSnoozeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_snooze), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(snooze.Snooze()) + await client.get_snooze(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"] + + +def test_get_snooze_flattened(): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = snooze.Snooze() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_snooze( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_snooze_flattened_error(): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_snooze( + snooze_service.GetSnoozeRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_snooze_flattened_async(): + client = SnoozeServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = snooze.Snooze() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(snooze.Snooze()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_snooze( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_snooze_flattened_error_async(): + client = SnoozeServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_snooze( + snooze_service.GetSnoozeRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + snooze_service.UpdateSnoozeRequest, + dict, + ], +) +def test_update_snooze(request_type, transport: str = "grpc"): + client = SnoozeServiceClient( + 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_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gm_snooze.Snooze( + name="name_value", + display_name="display_name_value", + ) + response = client.update_snooze(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.UpdateSnoozeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gm_snooze.Snooze) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +def test_update_snooze_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 = SnoozeServiceClient( + 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_snooze), "__call__") as call: + client.update_snooze() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.UpdateSnoozeRequest() + + +@pytest.mark.asyncio +async def test_update_snooze_async( + transport: str = "grpc_asyncio", request_type=snooze_service.UpdateSnoozeRequest +): + client = SnoozeServiceAsyncClient( + 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_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gm_snooze.Snooze( + name="name_value", + display_name="display_name_value", + ) + ) + response = await client.update_snooze(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == snooze_service.UpdateSnoozeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gm_snooze.Snooze) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_update_snooze_async_from_dict(): + await test_update_snooze_async(request_type=dict) + + +def test_update_snooze_field_headers(): + client = SnoozeServiceClient( + 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 = snooze_service.UpdateSnoozeRequest() + + request.snooze.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_snooze), "__call__") as call: + call.return_value = gm_snooze.Snooze() + client.update_snooze(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", + "snooze.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_snooze_field_headers_async(): + client = SnoozeServiceAsyncClient( + 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 = snooze_service.UpdateSnoozeRequest() + + request.snooze.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_snooze), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gm_snooze.Snooze()) + await client.update_snooze(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", + "snooze.name=name_value", + ) in kw["metadata"] + + +def test_update_snooze_flattened(): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gm_snooze.Snooze() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_snooze( + snooze=gm_snooze.Snooze(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].snooze + mock_val = gm_snooze.Snooze(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_snooze_flattened_error(): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_snooze( + snooze_service.UpdateSnoozeRequest(), + snooze=gm_snooze.Snooze(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_snooze_flattened_async(): + client = SnoozeServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_snooze), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gm_snooze.Snooze() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gm_snooze.Snooze()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_snooze( + snooze=gm_snooze.Snooze(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].snooze + mock_val = gm_snooze.Snooze(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_snooze_flattened_error_async(): + client = SnoozeServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_snooze( + snooze_service.UpdateSnoozeRequest(), + snooze=gm_snooze.Snooze(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SnoozeServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SnoozeServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SnoozeServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SnoozeServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SnoozeServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SnoozeServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SnoozeServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SnoozeServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SnoozeServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SnoozeServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SnoozeServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SnoozeServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SnoozeServiceGrpcTransport, + transports.SnoozeServiceGrpcAsyncIOTransport, + ], +) +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 = SnoozeServiceClient.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 = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SnoozeServiceGrpcTransport, + ) + + +def test_snooze_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SnoozeServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_snooze_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.monitoring_v3.services.snooze_service.transports.SnoozeServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SnoozeServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_snooze", + "list_snoozes", + "get_snooze", + "update_snooze", + ) + 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_snooze_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_v3.services.snooze_service.transports.SnoozeServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SnoozeServiceTransport( + 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", + ), + quota_project_id="octopus", + ) + + +def test_snooze_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_v3.services.snooze_service.transports.SnoozeServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SnoozeServiceTransport() + adc.assert_called_once() + + +def test_snooze_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) + SnoozeServiceClient() + 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", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SnoozeServiceGrpcTransport, + transports.SnoozeServiceGrpcAsyncIOTransport, + ], +) +def test_snooze_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", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SnoozeServiceGrpcTransport, + transports.SnoozeServiceGrpcAsyncIOTransport, + ], +) +def test_snooze_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.SnoozeServiceGrpcTransport, grpc_helpers), + (transports.SnoozeServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_snooze_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", + ), + 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.SnoozeServiceGrpcTransport, + transports.SnoozeServiceGrpcAsyncIOTransport, + ], +) +def test_snooze_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_snooze_service_host_no_port(transport_name): + client = SnoozeServiceClient( + 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_snooze_service_host_with_port(transport_name): + client = SnoozeServiceClient( + 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_snooze_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SnoozeServiceGrpcTransport( + 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_snooze_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SnoozeServiceGrpcAsyncIOTransport( + 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.SnoozeServiceGrpcTransport, + transports.SnoozeServiceGrpcAsyncIOTransport, + ], +) +def test_snooze_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.SnoozeServiceGrpcTransport, + transports.SnoozeServiceGrpcAsyncIOTransport, + ], +) +def test_snooze_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 = SnoozeServiceClient.alert_policy_path(project, alert_policy) + assert expected == actual + + +def test_parse_alert_policy_path(): + expected = { + "project": "whelk", + "alert_policy": "octopus", + } + path = SnoozeServiceClient.alert_policy_path(**expected) + + # Check that the path construction is reversible. + actual = SnoozeServiceClient.parse_alert_policy_path(path) + assert expected == actual + + +def test_snooze_path(): + project = "oyster" + snooze = "nudibranch" + expected = "projects/{project}/snoozes/{snooze}".format( + project=project, + snooze=snooze, + ) + actual = SnoozeServiceClient.snooze_path(project, snooze) + assert expected == actual + + +def test_parse_snooze_path(): + expected = { + "project": "cuttlefish", + "snooze": "mussel", + } + path = SnoozeServiceClient.snooze_path(**expected) + + # Check that the path construction is reversible. + actual = SnoozeServiceClient.parse_snooze_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SnoozeServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = SnoozeServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SnoozeServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SnoozeServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = SnoozeServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SnoozeServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SnoozeServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = SnoozeServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SnoozeServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = SnoozeServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = SnoozeServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SnoozeServiceClient.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 = SnoozeServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = SnoozeServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SnoozeServiceClient.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.SnoozeServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SnoozeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SnoozeServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SnoozeServiceClient.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 = SnoozeServiceAsyncClient( + 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 = SnoozeServiceClient( + 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 = SnoozeServiceClient( + 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", + [ + (SnoozeServiceClient, transports.SnoozeServiceGrpcTransport), + (SnoozeServiceAsyncClient, transports.SnoozeServiceGrpcAsyncIOTransport), + ], +) +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, + )