From 5381512872ca2492ddabcbdd7ccde5f054aed011 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Wed, 30 Dec 2020 08:14:21 -0800 Subject: [PATCH] feat: add experiments API (#36) --- docs/dialogflowcx_v3/services.rst | 3 + docs/dialogflowcx_v3beta1/services.rst | 6 + google/cloud/dialogflowcx/__init__.py | 28 + google/cloud/dialogflowcx_v3/__init__.py | 26 +- .../services/experiments/__init__.py | 24 + .../services/experiments/async_client.py | 705 +++++ .../services/experiments/client.py | 927 ++++++ .../services/experiments/pagers.py | 148 + .../experiments/transports/__init__.py | 35 + .../services/experiments/transports/base.py | 208 ++ .../services/experiments/transports/grpc.py | 443 +++ .../experiments/transports/grpc_asyncio.py | 450 +++ .../services/sessions/async_client.py | 25 +- .../services/sessions/client.py | 25 +- .../services/sessions/transports/grpc.py | 25 +- .../sessions/transports/grpc_asyncio.py | 25 +- .../cloud/dialogflowcx_v3/types/__init__.py | 24 + .../cloud/dialogflowcx_v3/types/experiment.py | 443 +++ google/cloud/dialogflowcx_v3/types/session.py | 38 +- google/cloud/dialogflowcx_v3beta1/__init__.py | 42 +- .../services/experiments/__init__.py | 24 + .../services/experiments/async_client.py | 707 +++++ .../services/experiments/client.py | 929 ++++++ .../services/experiments/pagers.py | 148 + .../experiments/transports/__init__.py | 35 + .../services/experiments/transports/base.py | 208 ++ .../services/experiments/transports/grpc.py | 445 +++ .../experiments/transports/grpc_asyncio.py | 452 +++ .../security_settings_service/__init__.py | 24 + .../security_settings_service/async_client.py | 572 ++++ .../security_settings_service/client.py | 767 +++++ .../security_settings_service/pagers.py | 152 + .../transports/__init__.py | 37 + .../transports/base.py | 201 ++ .../transports/grpc.py | 392 +++ .../transports/grpc_asyncio.py | 398 +++ .../dialogflowcx_v3beta1/types/__init__.py | 40 + .../dialogflowcx_v3beta1/types/experiment.py | 445 +++ .../types/response_message.py | 52 +- .../types/security_settings.py | 223 ++ .../dialogflowcx_v3beta1/types/session.py | 15 +- synth.metadata | 34 +- .../gapic/dialogflowcx_v3/test_experiments.py | 2571 ++++++++++++++++ .../dialogflowcx_v3beta1/test_experiments.py | 2573 +++++++++++++++++ .../test_security_settings_service.py | 2418 ++++++++++++++++ 45 files changed, 17432 insertions(+), 80 deletions(-) create mode 100644 google/cloud/dialogflowcx_v3/services/experiments/__init__.py create mode 100644 google/cloud/dialogflowcx_v3/services/experiments/async_client.py create mode 100644 google/cloud/dialogflowcx_v3/services/experiments/client.py create mode 100644 google/cloud/dialogflowcx_v3/services/experiments/pagers.py create mode 100644 google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py create mode 100644 google/cloud/dialogflowcx_v3/services/experiments/transports/base.py create mode 100644 google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py create mode 100644 google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py create mode 100644 google/cloud/dialogflowcx_v3/types/experiment.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/experiments/client.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py create mode 100644 google/cloud/dialogflowcx_v3beta1/types/experiment.py create mode 100644 google/cloud/dialogflowcx_v3beta1/types/security_settings.py create mode 100644 tests/unit/gapic/dialogflowcx_v3/test_experiments.py create mode 100644 tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py create mode 100644 tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py diff --git a/docs/dialogflowcx_v3/services.rst b/docs/dialogflowcx_v3/services.rst index eaaea2c8..958aa685 100644 --- a/docs/dialogflowcx_v3/services.rst +++ b/docs/dialogflowcx_v3/services.rst @@ -10,6 +10,9 @@ Services for Google Cloud Dialogflowcx v3 API .. automodule:: google.cloud.dialogflowcx_v3.services.environments :members: :inherited-members: +.. automodule:: google.cloud.dialogflowcx_v3.services.experiments + :members: + :inherited-members: .. automodule:: google.cloud.dialogflowcx_v3.services.flows :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/services.rst b/docs/dialogflowcx_v3beta1/services.rst index 917452b9..89e12040 100644 --- a/docs/dialogflowcx_v3beta1/services.rst +++ b/docs/dialogflowcx_v3beta1/services.rst @@ -10,6 +10,9 @@ Services for Google Cloud Dialogflowcx v3beta1 API .. automodule:: google.cloud.dialogflowcx_v3beta1.services.environments :members: :inherited-members: +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.experiments + :members: + :inherited-members: .. automodule:: google.cloud.dialogflowcx_v3beta1.services.flows :members: :inherited-members: @@ -19,6 +22,9 @@ Services for Google Cloud Dialogflowcx v3beta1 API .. automodule:: google.cloud.dialogflowcx_v3beta1.services.pages :members: :inherited-members: +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.security_settings_service + :members: + :inherited-members: .. automodule:: google.cloud.dialogflowcx_v3beta1.services.session_entity_types :members: :inherited-members: diff --git a/google/cloud/dialogflowcx/__init__.py b/google/cloud/dialogflowcx/__init__.py index 44462fe6..cc38b578 100644 --- a/google/cloud/dialogflowcx/__init__.py +++ b/google/cloud/dialogflowcx/__init__.py @@ -25,6 +25,10 @@ EnvironmentsAsyncClient, ) from google.cloud.dialogflowcx_v3.services.environments.client import EnvironmentsClient +from google.cloud.dialogflowcx_v3.services.experiments.async_client import ( + ExperimentsAsyncClient, +) +from google.cloud.dialogflowcx_v3.services.experiments.client import ExperimentsClient from google.cloud.dialogflowcx_v3.services.flows.async_client import FlowsAsyncClient from google.cloud.dialogflowcx_v3.services.flows.client import FlowsClient from google.cloud.dialogflowcx_v3.services.intents.async_client import ( @@ -103,6 +107,17 @@ LookupEnvironmentHistoryResponse, ) from google.cloud.dialogflowcx_v3.types.environment import UpdateEnvironmentRequest +from google.cloud.dialogflowcx_v3.types.experiment import CreateExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import DeleteExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import Experiment +from google.cloud.dialogflowcx_v3.types.experiment import GetExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import ListExperimentsRequest +from google.cloud.dialogflowcx_v3.types.experiment import ListExperimentsResponse +from google.cloud.dialogflowcx_v3.types.experiment import StartExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import StopExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import UpdateExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import VariantsHistory +from google.cloud.dialogflowcx_v3.types.experiment import VersionVariants from google.cloud.dialogflowcx_v3.types.flow import CreateFlowRequest from google.cloud.dialogflowcx_v3.types.flow import DeleteFlowRequest from google.cloud.dialogflowcx_v3.types.flow import Flow @@ -240,6 +255,7 @@ "CreateAgentRequest", "CreateEntityTypeRequest", "CreateEnvironmentRequest", + "CreateExperimentRequest", "CreateFlowRequest", "CreateIntentRequest", "CreatePageRequest", @@ -252,6 +268,7 @@ "DeleteAgentRequest", "DeleteEntityTypeRequest", "DeleteEnvironmentRequest", + "DeleteExperimentRequest", "DeleteFlowRequest", "DeleteIntentRequest", "DeletePageRequest", @@ -271,6 +288,9 @@ "EnvironmentsClient", "EventHandler", "EventInput", + "Experiment", + "ExperimentsAsyncClient", + "ExperimentsClient", "ExportAgentRequest", "ExportAgentResponse", "Flow", @@ -283,6 +303,7 @@ "GetAgentRequest", "GetEntityTypeRequest", "GetEnvironmentRequest", + "GetExperimentRequest", "GetFlowRequest", "GetIntentRequest", "GetPageRequest", @@ -303,6 +324,8 @@ "ListEntityTypesResponse", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "ListExperimentsRequest", + "ListExperimentsResponse", "ListFlowsRequest", "ListFlowsResponse", "ListIntentsRequest", @@ -351,6 +374,8 @@ "SpeechToTextSettings", "SpeechWordInfo", "SsmlVoiceGender", + "StartExperimentRequest", + "StopExperimentRequest", "StreamingDetectIntentRequest", "StreamingDetectIntentResponse", "StreamingRecognitionResult", @@ -364,6 +389,7 @@ "UpdateAgentRequest", "UpdateEntityTypeRequest", "UpdateEnvironmentRequest", + "UpdateExperimentRequest", "UpdateFlowRequest", "UpdateIntentRequest", "UpdatePageRequest", @@ -372,7 +398,9 @@ "UpdateTransitionRouteGroupRequest", "UpdateVersionRequest", "UpdateWebhookRequest", + "VariantsHistory", "Version", + "VersionVariants", "VersionsAsyncClient", "VersionsClient", "VoiceSelectionParams", diff --git a/google/cloud/dialogflowcx_v3/__init__.py b/google/cloud/dialogflowcx_v3/__init__.py index 246b530f..a897ab89 100644 --- a/google/cloud/dialogflowcx_v3/__init__.py +++ b/google/cloud/dialogflowcx_v3/__init__.py @@ -18,6 +18,7 @@ from .services.agents import AgentsClient from .services.entity_types import EntityTypesClient from .services.environments import EnvironmentsClient +from .services.experiments import ExperimentsClient from .services.flows import FlowsClient from .services.intents import IntentsClient from .services.pages import PagesClient @@ -63,6 +64,17 @@ from .types.environment import LookupEnvironmentHistoryRequest from .types.environment import LookupEnvironmentHistoryResponse from .types.environment import UpdateEnvironmentRequest +from .types.experiment import CreateExperimentRequest +from .types.experiment import DeleteExperimentRequest +from .types.experiment import Experiment +from .types.experiment import GetExperimentRequest +from .types.experiment import ListExperimentsRequest +from .types.experiment import ListExperimentsResponse +from .types.experiment import StartExperimentRequest +from .types.experiment import StopExperimentRequest +from .types.experiment import UpdateExperimentRequest +from .types.experiment import VariantsHistory +from .types.experiment import VersionVariants from .types.flow import CreateFlowRequest from .types.flow import DeleteFlowRequest from .types.flow import Flow @@ -162,6 +174,7 @@ "CreateAgentRequest", "CreateEntityTypeRequest", "CreateEnvironmentRequest", + "CreateExperimentRequest", "CreateFlowRequest", "CreateIntentRequest", "CreatePageRequest", @@ -174,6 +187,7 @@ "DeleteAgentRequest", "DeleteEntityTypeRequest", "DeleteEnvironmentRequest", + "DeleteExperimentRequest", "DeleteFlowRequest", "DeleteIntentRequest", "DeletePageRequest", @@ -186,11 +200,12 @@ "DetectIntentResponse", "DtmfInput", "EntityType", - "EntityTypesClient", "Environment", "EnvironmentsClient", "EventHandler", "EventInput", + "Experiment", + "ExperimentsClient", "ExportAgentRequest", "ExportAgentResponse", "Flow", @@ -202,6 +217,7 @@ "GetAgentRequest", "GetEntityTypeRequest", "GetEnvironmentRequest", + "GetExperimentRequest", "GetFlowRequest", "GetIntentRequest", "GetPageRequest", @@ -221,6 +237,8 @@ "ListEntityTypesResponse", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "ListExperimentsRequest", + "ListExperimentsResponse", "ListFlowsRequest", "ListFlowsResponse", "ListIntentsRequest", @@ -265,6 +283,8 @@ "SpeechToTextSettings", "SpeechWordInfo", "SsmlVoiceGender", + "StartExperimentRequest", + "StopExperimentRequest", "StreamingDetectIntentRequest", "StreamingDetectIntentResponse", "StreamingRecognitionResult", @@ -276,6 +296,7 @@ "UpdateAgentRequest", "UpdateEntityTypeRequest", "UpdateEnvironmentRequest", + "UpdateExperimentRequest", "UpdateFlowRequest", "UpdateIntentRequest", "UpdatePageRequest", @@ -284,12 +305,15 @@ "UpdateTransitionRouteGroupRequest", "UpdateVersionRequest", "UpdateWebhookRequest", + "VariantsHistory", "Version", + "VersionVariants", "VersionsClient", "VoiceSelectionParams", "Webhook", "WebhookRequest", "WebhookResponse", "WebhooksClient", + "EntityTypesClient", "TransitionRouteGroupsClient", ) diff --git a/google/cloud/dialogflowcx_v3/services/experiments/__init__.py b/google/cloud/dialogflowcx_v3/services/experiments/__init__.py new file mode 100644 index 00000000..c9141d08 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/experiments/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import ExperimentsClient +from .async_client import ExperimentsAsyncClient + +__all__ = ( + "ExperimentsClient", + "ExperimentsAsyncClient", +) diff --git a/google/cloud/dialogflowcx_v3/services/experiments/async_client.py b/google/cloud/dialogflowcx_v3/services/experiments/async_client.py new file mode 100644 index 00000000..137f0250 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/experiments/async_client.py @@ -0,0 +1,705 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.experiments import pagers +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport +from .client import ExperimentsClient + + +class ExperimentsAsyncClient: + """Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + """ + + _client: ExperimentsClient + + DEFAULT_ENDPOINT = ExperimentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ExperimentsClient.DEFAULT_MTLS_ENDPOINT + + experiment_path = staticmethod(ExperimentsClient.experiment_path) + parse_experiment_path = staticmethod(ExperimentsClient.parse_experiment_path) + version_path = staticmethod(ExperimentsClient.version_path) + parse_version_path = staticmethod(ExperimentsClient.parse_version_path) + + common_billing_account_path = staticmethod( + ExperimentsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ExperimentsClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(ExperimentsClient.common_folder_path) + parse_common_folder_path = staticmethod(ExperimentsClient.parse_common_folder_path) + + common_organization_path = staticmethod(ExperimentsClient.common_organization_path) + parse_common_organization_path = staticmethod( + ExperimentsClient.parse_common_organization_path + ) + + common_project_path = staticmethod(ExperimentsClient.common_project_path) + parse_common_project_path = staticmethod( + ExperimentsClient.parse_common_project_path + ) + + common_location_path = staticmethod(ExperimentsClient.common_location_path) + parse_common_location_path = staticmethod( + ExperimentsClient.parse_common_location_path + ) + + from_service_account_file = ExperimentsClient.from_service_account_file + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ExperimentsTransport: + """Return the transport used by the client instance. + + Returns: + ExperimentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(ExperimentsClient).get_transport_class, type(ExperimentsClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, ExperimentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the experiments 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, ~.ExperimentsTransport]): 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 = ExperimentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_experiments( + self, + request: experiment.ListExperimentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExperimentsAsyncPager: + r"""Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`~.experiment.ListExperimentsRequest`): + The request object. The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + parent (:class:`str`): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to list all environments for. Format: + ``projects//locations//agents//environments/``. + 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: + ~.pagers.ListExperimentsAsyncPager: + The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = experiment.ListExperimentsRequest(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_experiments, + default_timeout=None, + 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.ListExperimentsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_experiment( + self, + request: experiment.GetExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`~.experiment.GetExperimentRequest`): + The request object. The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = experiment.GetExperimentRequest(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_experiment, + default_timeout=None, + 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 create_experiment( + self, + request: gcdc_experiment.CreateExperimentRequest = None, + *, + parent: str = None, + experiment: gcdc_experiment.Experiment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`~.gcdc_experiment.CreateExperimentRequest`): + The request object. The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents//environments/``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + experiment (:class:`~.gcdc_experiment.Experiment`): + Required. The experiment to create. + This corresponds to the ``experiment`` 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: + ~.gcdc_experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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, experiment]) + 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 = gcdc_experiment.CreateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if experiment is not None: + request.experiment = experiment + + # 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_experiment, + default_timeout=None, + 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 update_experiment( + self, + request: gcdc_experiment.UpdateExperimentRequest = None, + *, + experiment: gcdc_experiment.Experiment = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`~.gcdc_experiment.UpdateExperimentRequest`): + The request object. The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. + experiment (:class:`~.gcdc_experiment.Experiment`): + Required. The experiment to update. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. The mask to control which + fields get 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: + ~.gcdc_experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([experiment, 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 = gcdc_experiment.UpdateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if experiment is not None: + request.experiment = experiment + 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_experiment, + default_timeout=None, + 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( + (("experiment.name", request.experiment.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_experiment( + self, + request: experiment.DeleteExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`~.experiment.DeleteExperimentRequest`): + The request object. The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = experiment.DeleteExperimentRequest(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.delete_experiment, + default_timeout=None, + 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. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def start_experiment( + self, + request: experiment.StartExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Args: + request (:class:`~.experiment.StartExperimentRequest`): + The request object. The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to start. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = experiment.StartExperimentRequest(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.start_experiment, + default_timeout=None, + 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 stop_experiment( + self, + request: experiment.StopExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Args: + request (:class:`~.experiment.StopExperimentRequest`): + The request object. The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to stop. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = experiment.StopExperimentRequest(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.stop_experiment, + default_timeout=None, + 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 + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ExperimentsAsyncClient",) diff --git a/google/cloud/dialogflowcx_v3/services/experiments/client.py b/google/cloud/dialogflowcx_v3/services/experiments/client.py new file mode 100644 index 00000000..9e0984a8 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/experiments/client.py @@ -0,0 +1,927 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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 + +from google.cloud.dialogflowcx_v3.services.experiments import pagers +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ExperimentsGrpcTransport +from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport + + +class ExperimentsClientMeta(type): + """Metaclass for the Experiments 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[ExperimentsTransport]] + _transport_registry["grpc"] = ExperimentsGrpcTransport + _transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ExperimentsTransport]: + """Return 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 ExperimentsClient(metaclass=ExperimentsClientMeta): + """Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ExperimentsTransport: + """Return the transport used by the client instance. + + Returns: + ExperimentsTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def experiment_path( + project: str, location: str, agent: str, environment: str, experiment: str, + ) -> str: + """Return a fully-qualified experiment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format( + project=project, + location=location, + agent=agent, + environment=environment, + experiment=experiment, + ) + + @staticmethod + def parse_experiment_path(path: str) -> Dict[str, str]: + """Parse a experiment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/experiments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def version_path( + project: str, location: str, agent: str, flow: str, version: str, + ) -> str: + """Return a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( + project=project, location=location, agent=agent, flow=flow, version=version, + ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str, str]: + """Parse a version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return 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: + """Return 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: + """Return 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: + """Return 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: + """Return 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 {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ExperimentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the experiments 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, ~.ExperimentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.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. + 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ExperimentsTransport): + # transport is a ExperimentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_experiments( + self, + request: experiment.ListExperimentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExperimentsPager: + r"""Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`~.experiment.ListExperimentsRequest`): + The request object. The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + parent (:class:`str`): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to list all environments for. Format: + ``projects//locations//agents//environments/``. + 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: + ~.pagers.ListExperimentsPager: + The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 experiment.ListExperimentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.ListExperimentsRequest): + request = experiment.ListExperimentsRequest(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_experiments] + + # 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.ListExperimentsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_experiment( + self, + request: experiment.GetExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`~.experiment.GetExperimentRequest`): + The request object. The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 experiment.GetExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.GetExperimentRequest): + request = experiment.GetExperimentRequest(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_experiment] + + # 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 create_experiment( + self, + request: gcdc_experiment.CreateExperimentRequest = None, + *, + parent: str = None, + experiment: gcdc_experiment.Experiment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`~.gcdc_experiment.CreateExperimentRequest`): + The request object. The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents//environments/``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + experiment (:class:`~.gcdc_experiment.Experiment`): + Required. The experiment to create. + This corresponds to the ``experiment`` 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: + ~.gcdc_experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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, experiment]) + 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 gcdc_experiment.CreateExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_experiment.CreateExperimentRequest): + request = gcdc_experiment.CreateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if experiment is not None: + request.experiment = experiment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_experiment] + + # 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 update_experiment( + self, + request: gcdc_experiment.UpdateExperimentRequest = None, + *, + experiment: gcdc_experiment.Experiment = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`~.gcdc_experiment.UpdateExperimentRequest`): + The request object. The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. + experiment (:class:`~.gcdc_experiment.Experiment`): + Required. The experiment to update. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. The mask to control which + fields get 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: + ~.gcdc_experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([experiment, 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 gcdc_experiment.UpdateExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_experiment.UpdateExperimentRequest): + request = gcdc_experiment.UpdateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if experiment is not None: + request.experiment = experiment + 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_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("experiment.name", request.experiment.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_experiment( + self, + request: experiment.DeleteExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`~.experiment.DeleteExperimentRequest`): + The request object. The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 experiment.DeleteExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.DeleteExperimentRequest): + request = experiment.DeleteExperimentRequest(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.delete_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def start_experiment( + self, + request: experiment.StartExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Args: + request (:class:`~.experiment.StartExperimentRequest`): + The request object. The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to start. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 experiment.StartExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.StartExperimentRequest): + request = experiment.StartExperimentRequest(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.start_experiment] + + # 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 stop_experiment( + self, + request: experiment.StopExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Args: + request (:class:`~.experiment.StopExperimentRequest`): + The request object. The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to stop. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 experiment.StopExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.StopExperimentRequest): + request = experiment.StopExperimentRequest(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.stop_experiment] + + # 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 + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ExperimentsClient",) diff --git a/google/cloud/dialogflowcx_v3/services/experiments/pagers.py b/google/cloud/dialogflowcx_v3/services/experiments/pagers.py new file mode 100644 index 00000000..248a0d06 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/experiments/pagers.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.dialogflowcx_v3.types import experiment + + +class ListExperimentsPager: + """A pager for iterating through ``list_experiments`` requests. + + This class thinly wraps an initial + :class:`~.experiment.ListExperimentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``experiments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExperiments`` requests and continue to iterate + through the ``experiments`` field on the + corresponding responses. + + All the usual :class:`~.experiment.ListExperimentsResponse` + 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[..., experiment.ListExperimentsResponse], + request: experiment.ListExperimentsRequest, + response: experiment.ListExperimentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.experiment.ListExperimentsRequest`): + The initial request object. + response (:class:`~.experiment.ListExperimentsResponse`): + 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 = experiment.ListExperimentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[experiment.ListExperimentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[experiment.Experiment]: + for page in self.pages: + yield from page.experiments + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListExperimentsAsyncPager: + """A pager for iterating through ``list_experiments`` requests. + + This class thinly wraps an initial + :class:`~.experiment.ListExperimentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``experiments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExperiments`` requests and continue to iterate + through the ``experiments`` field on the + corresponding responses. + + All the usual :class:`~.experiment.ListExperimentsResponse` + 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[experiment.ListExperimentsResponse]], + request: experiment.ListExperimentsRequest, + response: experiment.ListExperimentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.experiment.ListExperimentsRequest`): + The initial request object. + response (:class:`~.experiment.ListExperimentsResponse`): + 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 = experiment.ListExperimentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[experiment.ListExperimentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[experiment.Experiment]: + async def async_generator(): + async for page in self.pages: + for response in page.experiments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py new file mode 100644 index 00000000..d1972e23 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import ExperimentsTransport +from .grpc import ExperimentsGrpcTransport +from .grpc_asyncio import ExperimentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ExperimentsTransport]] +_transport_registry["grpc"] = ExperimentsGrpcTransport +_transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport + +__all__ = ( + "ExperimentsTransport", + "ExperimentsGrpcTransport", + "ExperimentsGrpcAsyncIOTransport", +) diff --git a/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py b/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py new file mode 100644 index 00000000..a476c814 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ExperimentsTransport(abc.ABC): + """Abstract transport class for Experiments.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **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. + scope (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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_experiments: gapic_v1.method.wrap_method( + self.list_experiments, default_timeout=None, client_info=client_info, + ), + self.get_experiment: gapic_v1.method.wrap_method( + self.get_experiment, default_timeout=None, client_info=client_info, + ), + self.create_experiment: gapic_v1.method.wrap_method( + self.create_experiment, default_timeout=None, client_info=client_info, + ), + self.update_experiment: gapic_v1.method.wrap_method( + self.update_experiment, default_timeout=None, client_info=client_info, + ), + self.delete_experiment: gapic_v1.method.wrap_method( + self.delete_experiment, default_timeout=None, client_info=client_info, + ), + self.start_experiment: gapic_v1.method.wrap_method( + self.start_experiment, default_timeout=None, client_info=client_info, + ), + self.stop_experiment: gapic_v1.method.wrap_method( + self.stop_experiment, default_timeout=None, client_info=client_info, + ), + } + + @property + def list_experiments( + self, + ) -> typing.Callable[ + [experiment.ListExperimentsRequest], + typing.Union[ + experiment.ListExperimentsResponse, + typing.Awaitable[experiment.ListExperimentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_experiment( + self, + ) -> typing.Callable[ + [experiment.GetExperimentRequest], + typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + ]: + raise NotImplementedError() + + @property + def create_experiment( + self, + ) -> typing.Callable[ + [gcdc_experiment.CreateExperimentRequest], + typing.Union[ + gcdc_experiment.Experiment, typing.Awaitable[gcdc_experiment.Experiment] + ], + ]: + raise NotImplementedError() + + @property + def update_experiment( + self, + ) -> typing.Callable[ + [gcdc_experiment.UpdateExperimentRequest], + typing.Union[ + gcdc_experiment.Experiment, typing.Awaitable[gcdc_experiment.Experiment] + ], + ]: + raise NotImplementedError() + + @property + def delete_experiment( + self, + ) -> typing.Callable[ + [experiment.DeleteExperimentRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def start_experiment( + self, + ) -> typing.Callable[ + [experiment.StartExperimentRequest], + typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + ]: + raise NotImplementedError() + + @property + def stop_experiment( + self, + ) -> typing.Callable[ + [experiment.StopExperimentRequest], + typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + ]: + raise NotImplementedError() + + +__all__ = ("ExperimentsTransport",) diff --git a/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py new file mode 100644 index 00000000..316128d2 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py @@ -0,0 +1,443 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO + + +class ExperimentsGrpcTransport(ExperimentsTransport): + """gRPC backend transport for Experiments. + + Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + + 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 = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 applicatin 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 grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + 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._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_experiments( + self, + ) -> Callable[ + [experiment.ListExperimentsRequest], experiment.ListExperimentsResponse + ]: + r"""Return a callable for the list experiments method over gRPC. + + Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.ListExperimentsRequest], + ~.ListExperimentsResponse]: + 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_experiments" not in self._stubs: + self._stubs["list_experiments"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/ListExperiments", + request_serializer=experiment.ListExperimentsRequest.serialize, + response_deserializer=experiment.ListExperimentsResponse.deserialize, + ) + return self._stubs["list_experiments"] + + @property + def get_experiment( + self, + ) -> Callable[[experiment.GetExperimentRequest], experiment.Experiment]: + r"""Return a callable for the get experiment method over gRPC. + + Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.GetExperimentRequest], + ~.Experiment]: + 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_experiment" not in self._stubs: + self._stubs["get_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/GetExperiment", + request_serializer=experiment.GetExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["get_experiment"] + + @property + def create_experiment( + self, + ) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], gcdc_experiment.Experiment + ]: + r"""Return a callable for the create experiment method over gRPC. + + Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.CreateExperimentRequest], + ~.Experiment]: + 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_experiment" not in self._stubs: + self._stubs["create_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/CreateExperiment", + request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs["create_experiment"] + + @property + def update_experiment( + self, + ) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], gcdc_experiment.Experiment + ]: + r"""Return a callable for the update experiment method over gRPC. + + Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.UpdateExperimentRequest], + ~.Experiment]: + 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_experiment" not in self._stubs: + self._stubs["update_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/UpdateExperiment", + request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs["update_experiment"] + + @property + def delete_experiment( + self, + ) -> Callable[[experiment.DeleteExperimentRequest], empty.Empty]: + r"""Return a callable for the delete experiment method over gRPC. + + Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.DeleteExperimentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_experiment" not in self._stubs: + self._stubs["delete_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/DeleteExperiment", + request_serializer=experiment.DeleteExperimentRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_experiment"] + + @property + def start_experiment( + self, + ) -> Callable[[experiment.StartExperimentRequest], experiment.Experiment]: + r"""Return a callable for the start experiment method over gRPC. + + Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Returns: + Callable[[~.StartExperimentRequest], + ~.Experiment]: + 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 "start_experiment" not in self._stubs: + self._stubs["start_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/StartExperiment", + request_serializer=experiment.StartExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["start_experiment"] + + @property + def stop_experiment( + self, + ) -> Callable[[experiment.StopExperimentRequest], experiment.Experiment]: + r"""Return a callable for the stop experiment method over gRPC. + + Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Returns: + Callable[[~.StopExperimentRequest], + ~.Experiment]: + 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 "stop_experiment" not in self._stubs: + self._stubs["stop_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/StopExperiment", + request_serializer=experiment.StopExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["stop_experiment"] + + +__all__ = ("ExperimentsGrpcTransport",) diff --git a/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py new file mode 100644 index 00000000..43f61395 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py @@ -0,0 +1,450 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import 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.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .grpc import ExperimentsGrpcTransport + + +class ExperimentsGrpcAsyncIOTransport(ExperimentsTransport): + """gRPC AsyncIO backend transport for Experiments. + + Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + + 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 = "dialogflow.googleapis.com", + credentials: 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: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 applicatin 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 grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + 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._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_experiments( + self, + ) -> Callable[ + [experiment.ListExperimentsRequest], + Awaitable[experiment.ListExperimentsResponse], + ]: + r"""Return a callable for the list experiments method over gRPC. + + Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.ListExperimentsRequest], + Awaitable[~.ListExperimentsResponse]]: + 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_experiments" not in self._stubs: + self._stubs["list_experiments"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/ListExperiments", + request_serializer=experiment.ListExperimentsRequest.serialize, + response_deserializer=experiment.ListExperimentsResponse.deserialize, + ) + return self._stubs["list_experiments"] + + @property + def get_experiment( + self, + ) -> Callable[[experiment.GetExperimentRequest], Awaitable[experiment.Experiment]]: + r"""Return a callable for the get experiment method over gRPC. + + Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.GetExperimentRequest], + Awaitable[~.Experiment]]: + 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_experiment" not in self._stubs: + self._stubs["get_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/GetExperiment", + request_serializer=experiment.GetExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["get_experiment"] + + @property + def create_experiment( + self, + ) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], Awaitable[gcdc_experiment.Experiment] + ]: + r"""Return a callable for the create experiment method over gRPC. + + Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.CreateExperimentRequest], + Awaitable[~.Experiment]]: + 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_experiment" not in self._stubs: + self._stubs["create_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/CreateExperiment", + request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs["create_experiment"] + + @property + def update_experiment( + self, + ) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], Awaitable[gcdc_experiment.Experiment] + ]: + r"""Return a callable for the update experiment method over gRPC. + + Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.UpdateExperimentRequest], + Awaitable[~.Experiment]]: + 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_experiment" not in self._stubs: + self._stubs["update_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/UpdateExperiment", + request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs["update_experiment"] + + @property + def delete_experiment( + self, + ) -> Callable[[experiment.DeleteExperimentRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete experiment method over gRPC. + + Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.DeleteExperimentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_experiment" not in self._stubs: + self._stubs["delete_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/DeleteExperiment", + request_serializer=experiment.DeleteExperimentRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_experiment"] + + @property + def start_experiment( + self, + ) -> Callable[ + [experiment.StartExperimentRequest], Awaitable[experiment.Experiment] + ]: + r"""Return a callable for the start experiment method over gRPC. + + Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Returns: + Callable[[~.StartExperimentRequest], + Awaitable[~.Experiment]]: + 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 "start_experiment" not in self._stubs: + self._stubs["start_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/StartExperiment", + request_serializer=experiment.StartExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["start_experiment"] + + @property + def stop_experiment( + self, + ) -> Callable[[experiment.StopExperimentRequest], Awaitable[experiment.Experiment]]: + r"""Return a callable for the stop experiment method over gRPC. + + Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Returns: + Callable[[~.StopExperimentRequest], + Awaitable[~.Experiment]]: + 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 "stop_experiment" not in self._stubs: + self._stubs["stop_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Experiments/StopExperiment", + request_serializer=experiment.StopExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["stop_experiment"] + + +__all__ = ("ExperimentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3/services/sessions/async_client.py b/google/cloud/dialogflowcx_v3/services/sessions/async_client.py index 624df4af..fe65ea1d 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/async_client.py @@ -174,11 +174,14 @@ async def detect_intent( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.DetectIntentResponse: - r"""Processes a natural language query and returns - structured, actionable data as a result. This method is - not idempotent, because it may cause session entity - types to be updated, which in turn might affect results - of future queries. + r"""Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause session entity types to be updated, which + in turn might affect results of future queries. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. Args: request (:class:`~.session.DetectIntentRequest`): @@ -234,10 +237,14 @@ def streaming_detect_intent( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> Awaitable[AsyncIterable[session.StreamingDetectIntentResponse]]: - r"""Processes a natural language query in audio format in - a streaming fashion and returns structured, actionable - data as a result. This method is only available via the - gRPC API (not REST). + r"""Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. Args: requests (AsyncIterator[`~.session.StreamingDetectIntentRequest`]): diff --git a/google/cloud/dialogflowcx_v3/services/sessions/client.py b/google/cloud/dialogflowcx_v3/services/sessions/client.py index 94988181..e9fcdbca 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/client.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/client.py @@ -480,11 +480,14 @@ def detect_intent( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.DetectIntentResponse: - r"""Processes a natural language query and returns - structured, actionable data as a result. This method is - not idempotent, because it may cause session entity - types to be updated, which in turn might affect results - of future queries. + r"""Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause session entity types to be updated, which + in turn might affect results of future queries. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. Args: request (:class:`~.session.DetectIntentRequest`): @@ -535,10 +538,14 @@ def streaming_detect_intent( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> Iterable[session.StreamingDetectIntentResponse]: - r"""Processes a natural language query in audio format in - a streaming fashion and returns structured, actionable - data as a result. This method is only available via the - gRPC API (not REST). + r"""Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. Args: requests (Iterator[`~.session.StreamingDetectIntentRequest`]): diff --git a/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py index 8c59047a..b12713d7 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py @@ -246,11 +246,14 @@ def detect_intent( ) -> Callable[[session.DetectIntentRequest], session.DetectIntentResponse]: r"""Return a callable for the detect intent method over gRPC. - Processes a natural language query and returns - structured, actionable data as a result. This method is - not idempotent, because it may cause session entity - types to be updated, which in turn might affect results - of future queries. + Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause session entity types to be updated, which + in turn might affect results of future queries. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. Returns: Callable[[~.DetectIntentRequest], @@ -278,10 +281,14 @@ def streaming_detect_intent( ]: r"""Return a callable for the streaming detect intent method over gRPC. - Processes a natural language query in audio format in - a streaming fashion and returns structured, actionable - data as a result. This method is only available via the - gRPC API (not REST). + Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. Returns: Callable[[~.StreamingDetectIntentRequest], diff --git a/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py index 795c6296..f8e6e3dd 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py @@ -252,11 +252,14 @@ def detect_intent( ]: r"""Return a callable for the detect intent method over gRPC. - Processes a natural language query and returns - structured, actionable data as a result. This method is - not idempotent, because it may cause session entity - types to be updated, which in turn might affect results - of future queries. + Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause session entity types to be updated, which + in turn might affect results of future queries. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. Returns: Callable[[~.DetectIntentRequest], @@ -285,10 +288,14 @@ def streaming_detect_intent( ]: r"""Return a callable for the streaming detect intent method over gRPC. - Processes a natural language query in audio format in - a streaming fashion and returns structured, actionable - data as a result. This method is only available via the - gRPC API (not REST). + Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. Returns: Callable[[~.StreamingDetectIntentRequest], diff --git a/google/cloud/dialogflowcx_v3/types/__init__.py b/google/cloud/dialogflowcx_v3/types/__init__.py index c6f076b4..fc0ebbf8 100644 --- a/google/cloud/dialogflowcx_v3/types/__init__.py +++ b/google/cloud/dialogflowcx_v3/types/__init__.py @@ -84,6 +84,19 @@ LookupEnvironmentHistoryRequest, LookupEnvironmentHistoryResponse, ) +from .experiment import ( + Experiment, + VersionVariants, + VariantsHistory, + ListExperimentsRequest, + ListExperimentsResponse, + GetExperimentRequest, + CreateExperimentRequest, + UpdateExperimentRequest, + DeleteExperimentRequest, + StartExperimentRequest, + StopExperimentRequest, +) from .intent import ( Intent, ListIntentsRequest, @@ -225,6 +238,17 @@ "DeleteEnvironmentRequest", "LookupEnvironmentHistoryRequest", "LookupEnvironmentHistoryResponse", + "Experiment", + "VersionVariants", + "VariantsHistory", + "ListExperimentsRequest", + "ListExperimentsResponse", + "GetExperimentRequest", + "CreateExperimentRequest", + "UpdateExperimentRequest", + "DeleteExperimentRequest", + "StartExperimentRequest", + "StopExperimentRequest", "Intent", "ListIntentsRequest", "ListIntentsResponse", diff --git a/google/cloud/dialogflowcx_v3/types/experiment.py b/google/cloud/dialogflowcx_v3/types/experiment.py new file mode 100644 index 00000000..6a4bda5d --- /dev/null +++ b/google/cloud/dialogflowcx_v3/types/experiment.py @@ -0,0 +1,443 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "Experiment", + "VersionVariants", + "VariantsHistory", + "ListExperimentsRequest", + "ListExperimentsResponse", + "GetExperimentRequest", + "CreateExperimentRequest", + "UpdateExperimentRequest", + "DeleteExperimentRequest", + "StartExperimentRequest", + "StopExperimentRequest", + }, +) + + +class Experiment(proto.Message): + r"""Represents an experiment in an environment. + Next ID: 13 + + Attributes: + name (str): + The name of the experiment. + Format: projects//locations//agents//environments//experiments/.. + display_name (str): + Required. The human-readable name of the + experiment (unique in an environment). Limit of + 64 characters. + description (str): + The human-readable description of the + experiment. + state (~.gcdc_experiment.Experiment.State): + The current state of the experiment. + Transition triggered by + Expriments.StartExperiment: PENDING->RUNNING. + Transition triggered by + Expriments.CancelExperiment: PENDING->CANCELLED + or RUNNING->CANCELLED. + definition (~.gcdc_experiment.Experiment.Definition): + The definition of the experiment. + result (~.gcdc_experiment.Experiment.Result): + Inference result of the experiment. + create_time (~.timestamp.Timestamp): + Creation time of this experiment. + start_time (~.timestamp.Timestamp): + Start time of this experiment. + end_time (~.timestamp.Timestamp): + End time of this experiment. + last_update_time (~.timestamp.Timestamp): + Last update time of this experiment. + experiment_length (~.duration.Duration): + Maximum number of days to run the experiment. + variants_history (Sequence[~.gcdc_experiment.VariantsHistory]): + The history of updates to the experiment + variants. + """ + + class State(proto.Enum): + r"""The state of the experiment.""" + STATE_UNSPECIFIED = 0 + DRAFT = 1 + RUNNING = 2 + DONE = 3 + + class Definition(proto.Message): + r"""Definition of the experiment. + Next ID: 3 + + Attributes: + condition (str): + The condition defines which subset of sessions are selected + for this experiment. If not specified, all sessions are + eligible. E.g. "query_input.language_code=en" See the + `conditions + reference `__. + version_variants (~.gcdc_experiment.VersionVariants): + The flow versions as the variants of this + experiment. + """ + + condition = proto.Field(proto.STRING, number=1) + + version_variants = proto.Field( + proto.MESSAGE, number=2, oneof="variants", message="VersionVariants", + ) + + class Result(proto.Message): + r"""The inference result which includes an objective metric to + optimize and the confidence interval. + + Attributes: + version_metrics (Sequence[~.gcdc_experiment.Experiment.Result.VersionMetrics]): + Version variants and metrics. + last_update_time (~.timestamp.Timestamp): + The last time the experiment's stats data was + updated. Will have default value if stats have + never been computed for this experiment. + """ + + class MetricType(proto.Enum): + r"""Types of metric for Dialogflow experiment.""" + METRIC_UNSPECIFIED = 0 + CONTAINED_SESSION_NO_CALLBACK_RATE = 1 + LIVE_AGENT_HANDOFF_RATE = 2 + CALLBACK_SESSION_RATE = 3 + ABANDONED_SESSION_RATE = 4 + SESSION_END_RATE = 5 + + class ConfidenceInterval(proto.Message): + r"""A confidence interval is a range of possible values for the + experiment objective you are trying to measure. + + Attributes: + confidence_level (float): + The confidence level used to construct the + interval, i.e. there is X% chance that the true + value is within this interval. + ratio (float): + The percent change between an experiment + metric's value and the value for its control. + lower_bound (float): + Lower bound of the interval. + upper_bound (float): + Upper bound of the interval. + """ + + confidence_level = proto.Field(proto.DOUBLE, number=1) + + ratio = proto.Field(proto.DOUBLE, number=2) + + lower_bound = proto.Field(proto.DOUBLE, number=3) + + upper_bound = proto.Field(proto.DOUBLE, number=4) + + class Metric(proto.Message): + r"""Metric and corresponding confidence intervals. + + Attributes: + type_ (~.gcdc_experiment.Experiment.Result.MetricType): + The type of the metric. + ratio (float): + Ratio value of a metric. + confidence_interval (~.gcdc_experiment.Experiment.Result.ConfidenceInterval): + The probability that the treatment is better + than all other treatments in the experiment + """ + + type_ = proto.Field( + proto.ENUM, number=1, enum="Experiment.Result.MetricType", + ) + + ratio = proto.Field(proto.DOUBLE, number=2, oneof="value") + + confidence_interval = proto.Field( + proto.MESSAGE, number=3, message="Experiment.Result.ConfidenceInterval", + ) + + class VersionMetrics(proto.Message): + r"""Version variant and associated metrics. + + Attributes: + version (str): + The name of the flow + [Version][google.cloud.dialogflow.cx.v3.Version]. Format: + ``projects//locations//agents//flows//versions/``. + metrics (Sequence[~.gcdc_experiment.Experiment.Result.Metric]): + The metrics and corresponding confidence + intervals in the inference result. + session_count (int): + Number of sessions that were allocated to + this version. + """ + + version = proto.Field(proto.STRING, number=1) + + metrics = proto.RepeatedField( + proto.MESSAGE, number=2, message="Experiment.Result.Metric", + ) + + session_count = proto.Field(proto.INT32, number=3) + + version_metrics = proto.RepeatedField( + proto.MESSAGE, number=1, message="Experiment.Result.VersionMetrics", + ) + + last_update_time = proto.Field( + proto.MESSAGE, number=2, message=timestamp.Timestamp, + ) + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + state = proto.Field(proto.ENUM, number=4, enum=State,) + + definition = proto.Field(proto.MESSAGE, number=5, message=Definition,) + + result = proto.Field(proto.MESSAGE, number=6, message=Result,) + + create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) + + start_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + last_update_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp.Timestamp, + ) + + experiment_length = proto.Field( + proto.MESSAGE, number=11, message=duration.Duration, + ) + + variants_history = proto.RepeatedField( + proto.MESSAGE, number=12, message="VariantsHistory", + ) + + +class VersionVariants(proto.Message): + r"""A list of flow version variants. + + Attributes: + variants (Sequence[~.gcdc_experiment.VersionVariants.Variant]): + A list of flow version variants. + """ + + class Variant(proto.Message): + r"""A single flow version with specified traffic allocation. + + Attributes: + version (str): + The name of the flow version. Format: + ``projects//locations//agents//flows//versions/``. + traffic_allocation (float): + Percentage of the traffic which should be + routed to this version of flow. Traffic + allocation for a single flow must sum up to 1.0. + is_control_group (bool): + Whether the variant is for the control group. + """ + + version = proto.Field(proto.STRING, number=1) + + traffic_allocation = proto.Field(proto.FLOAT, number=2) + + is_control_group = proto.Field(proto.BOOL, number=3) + + variants = proto.RepeatedField(proto.MESSAGE, number=1, message=Variant,) + + +class VariantsHistory(proto.Message): + r"""The history of variants update. + + Attributes: + version_variants (~.gcdc_experiment.VersionVariants): + The flow versions as the variants. + update_time (~.timestamp.Timestamp): + Update time of the variants. + """ + + version_variants = proto.Field( + proto.MESSAGE, number=1, oneof="variants", message="VersionVariants", + ) + + update_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + +class ListExperimentsRequest(proto.Message): + r"""The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + Attributes: + parent (str): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] to + list all environments for. Format: + ``projects//locations//agents//environments/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListExperimentsResponse(proto.Message): + r"""The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + Attributes: + experiments (Sequence[~.gcdc_experiment.Experiment]): + The list of experiments. There will be a maximum number of + items returned based on the page_size field in the request. + The list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + experiments = proto.RepeatedField(proto.MESSAGE, number=1, message="Experiment",) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetExperimentRequest(proto.Message): + r"""The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateExperimentRequest(proto.Message): + r"""The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. + + Attributes: + parent (str): + Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] + to create an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents//environments/``. + experiment (~.gcdc_experiment.Experiment): + Required. The experiment to create. + """ + + parent = proto.Field(proto.STRING, number=1) + + experiment = proto.Field(proto.MESSAGE, number=2, message="Experiment",) + + +class UpdateExperimentRequest(proto.Message): + r"""The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. + + Attributes: + experiment (~.gcdc_experiment.Experiment): + Required. The experiment to update. + update_mask (~.field_mask.FieldMask): + Required. The mask to control which fields + get updated. + """ + + experiment = proto.Field(proto.MESSAGE, number=1, message="Experiment",) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteExperimentRequest(proto.Message): + r"""The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] to + delete. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class StartExperimentRequest(proto.Message): + r"""The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. + + Attributes: + name (str): + Required. Resource name of the experiment to start. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class StopExperimentRequest(proto.Message): + r"""The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. + + Attributes: + name (str): + Required. Resource name of the experiment to stop. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field(proto.STRING, number=1) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/session.py b/google/cloud/dialogflowcx_v3/types/session.py index ffdc877a..b0876d07 100644 --- a/google/cloud/dialogflowcx_v3/types/session.py +++ b/google/cloud/dialogflowcx_v3/types/session.py @@ -73,6 +73,10 @@ class DetectIntentRequest(proto.Message): For more information, see the `sessions guide `__. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. query_params (~.gcdc_session.QueryParameters): The parameters of this query. query_input (~.gcdc_session.QueryInput): @@ -185,6 +189,10 @@ class StreamingDetectIntentRequest(proto.Message): For more information, see the `sessions guide `__. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. query_params (~.gcdc_session.QueryParameters): The parameters of this query. query_input (~.gcdc_session.QueryInput): @@ -373,8 +381,8 @@ class QueryParameters(proto.Message): - MapValue type: - If parameter's entity type is a composite entity: map - - Else: string or number, depending on parameter value - type + - Else: depending on parameter value type, could be one + of string, number, boolean, null, list or map - MapValue value: @@ -386,6 +394,19 @@ class QueryParameters(proto.Message): Configures whether sentiment analysis should be performed. If not provided, sentiment analysis is not performed. + webhook_headers (Sequence[~.gcdc_session.QueryParameters.WebhookHeadersEntry]): + This field can be used to pass HTTP headers + for a webhook call. These headers will be sent + to webhook along with the headers that have been + configured through Dialogflow web console. The + headers defined within this field will overwrite + the headers configured through Dialogflow + console if there is a conflict. Header names are + case-insensitive. Google's specified headers are + not allowed. Including: "Host", "Content- + Length", "Connection", "From", "User-Agent", + "Accept-Encoding", "If-Modified-Since", "If- + None-Match", "X-Forwarded-For", etc. """ time_zone = proto.Field(proto.STRING, number=1) @@ -402,6 +423,8 @@ class QueryParameters(proto.Message): analyze_query_text_sentiment = proto.Field(proto.BOOL, number=8) + webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=10) + class QueryInput(proto.Message): r"""Represents the query input. It can contain one of: @@ -485,8 +508,8 @@ class QueryResult(proto.Message): - MapValue type: - If parameter's entity type is a composite entity: map - - Else: string or number, depending on parameter value - type + - Else: depending on parameter value type, could be one + of string, number, boolean, null, list or map - MapValue value: @@ -690,9 +713,10 @@ class Match(proto.Message): - MapKey value: parameter name - MapValue type: - If parameter's entity type is a - composite entity: map - Else: string or - number, depending on parameter value type - - MapValue value: + composite entity: map - Else: depending on + parameter value type, could be one of string, + number, boolean, null, list or map + - MapValue value: - If parameter's entity type is a composite entity: map from composite entity property names to property values - diff --git a/google/cloud/dialogflowcx_v3beta1/__init__.py b/google/cloud/dialogflowcx_v3beta1/__init__.py index b3a7bf55..f78a8e10 100644 --- a/google/cloud/dialogflowcx_v3beta1/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/__init__.py @@ -18,9 +18,11 @@ from .services.agents import AgentsClient from .services.entity_types import EntityTypesClient from .services.environments import EnvironmentsClient +from .services.experiments import ExperimentsClient from .services.flows import FlowsClient from .services.intents import IntentsClient from .services.pages import PagesClient +from .services.security_settings_service import SecuritySettingsServiceClient from .services.session_entity_types import SessionEntityTypesClient from .services.sessions import SessionsClient from .services.transition_route_groups import TransitionRouteGroupsClient @@ -62,6 +64,17 @@ from .types.environment import LookupEnvironmentHistoryRequest from .types.environment import LookupEnvironmentHistoryResponse from .types.environment import UpdateEnvironmentRequest +from .types.experiment import CreateExperimentRequest +from .types.experiment import DeleteExperimentRequest +from .types.experiment import Experiment +from .types.experiment import GetExperimentRequest +from .types.experiment import ListExperimentsRequest +from .types.experiment import ListExperimentsResponse +from .types.experiment import StartExperimentRequest +from .types.experiment import StopExperimentRequest +from .types.experiment import UpdateExperimentRequest +from .types.experiment import VariantsHistory +from .types.experiment import VersionVariants from .types.flow import CreateFlowRequest from .types.flow import DeleteFlowRequest from .types.flow import Flow @@ -91,6 +104,13 @@ from .types.page import TransitionRoute from .types.page import UpdatePageRequest from .types.response_message import ResponseMessage +from .types.security_settings import CreateSecuritySettingsRequest +from .types.security_settings import DeleteSecuritySettingsRequest +from .types.security_settings import GetSecuritySettingsRequest +from .types.security_settings import ListSecuritySettingsRequest +from .types.security_settings import ListSecuritySettingsResponse +from .types.security_settings import SecuritySettings +from .types.security_settings import UpdateSecuritySettingsRequest from .types.session import AudioInput from .types.session import DetectIntentRequest from .types.session import DetectIntentResponse @@ -148,15 +168,16 @@ __all__ = ( "Agent", - "AgentsClient", "AudioEncoding", "AudioInput", "CreateAgentRequest", "CreateEntityTypeRequest", "CreateEnvironmentRequest", + "CreateExperimentRequest", "CreateFlowRequest", "CreateIntentRequest", "CreatePageRequest", + "CreateSecuritySettingsRequest", "CreateSessionEntityTypeRequest", "CreateTransitionRouteGroupRequest", "CreateVersionOperationMetadata", @@ -165,9 +186,11 @@ "DeleteAgentRequest", "DeleteEntityTypeRequest", "DeleteEnvironmentRequest", + "DeleteExperimentRequest", "DeleteFlowRequest", "DeleteIntentRequest", "DeletePageRequest", + "DeleteSecuritySettingsRequest", "DeleteSessionEntityTypeRequest", "DeleteTransitionRouteGroupRequest", "DeleteVersionRequest", @@ -180,6 +203,8 @@ "EnvironmentsClient", "EventHandler", "EventInput", + "Experiment", + "ExperimentsClient", "ExportAgentRequest", "ExportAgentResponse", "Flow", @@ -191,9 +216,11 @@ "GetAgentRequest", "GetEntityTypeRequest", "GetEnvironmentRequest", + "GetExperimentRequest", "GetFlowRequest", "GetIntentRequest", "GetPageRequest", + "GetSecuritySettingsRequest", "GetSessionEntityTypeRequest", "GetTransitionRouteGroupRequest", "GetVersionRequest", @@ -209,12 +236,16 @@ "ListEntityTypesResponse", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "ListExperimentsRequest", + "ListExperimentsResponse", "ListFlowsRequest", "ListFlowsResponse", "ListIntentsRequest", "ListIntentsResponse", "ListPagesRequest", "ListPagesResponse", + "ListSecuritySettingsRequest", + "ListSecuritySettingsResponse", "ListSessionEntityTypesRequest", "ListSessionEntityTypesResponse", "ListTransitionRouteGroupsRequest", @@ -240,6 +271,8 @@ "QueryResult", "ResponseMessage", "RestoreAgentRequest", + "SecuritySettings", + "SecuritySettingsServiceClient", "SentimentAnalysisResult", "SessionEntityType", "SessionEntityTypesClient", @@ -249,6 +282,8 @@ "SpeechToTextSettings", "SpeechWordInfo", "SsmlVoiceGender", + "StartExperimentRequest", + "StopExperimentRequest", "StreamingDetectIntentRequest", "StreamingDetectIntentResponse", "StreamingRecognitionResult", @@ -261,19 +296,24 @@ "UpdateAgentRequest", "UpdateEntityTypeRequest", "UpdateEnvironmentRequest", + "UpdateExperimentRequest", "UpdateFlowRequest", "UpdateIntentRequest", "UpdatePageRequest", + "UpdateSecuritySettingsRequest", "UpdateSessionEntityTypeRequest", "UpdateTransitionRouteGroupRequest", "UpdateVersionRequest", "UpdateWebhookRequest", + "VariantsHistory", "Version", + "VersionVariants", "VersionsClient", "VoiceSelectionParams", "Webhook", "WebhookRequest", "WebhookResponse", "WebhooksClient", + "AgentsClient", "EntityTypesClient", ) diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py new file mode 100644 index 00000000..c9141d08 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import ExperimentsClient +from .async_client import ExperimentsAsyncClient + +__all__ = ( + "ExperimentsClient", + "ExperimentsAsyncClient", +) diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py new file mode 100644 index 00000000..6911f807 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py @@ -0,0 +1,707 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3beta1.services.experiments import pagers +from google.cloud.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport +from .client import ExperimentsClient + + +class ExperimentsAsyncClient: + """Service for managing + [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. + """ + + _client: ExperimentsClient + + DEFAULT_ENDPOINT = ExperimentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ExperimentsClient.DEFAULT_MTLS_ENDPOINT + + experiment_path = staticmethod(ExperimentsClient.experiment_path) + parse_experiment_path = staticmethod(ExperimentsClient.parse_experiment_path) + version_path = staticmethod(ExperimentsClient.version_path) + parse_version_path = staticmethod(ExperimentsClient.parse_version_path) + + common_billing_account_path = staticmethod( + ExperimentsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ExperimentsClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(ExperimentsClient.common_folder_path) + parse_common_folder_path = staticmethod(ExperimentsClient.parse_common_folder_path) + + common_organization_path = staticmethod(ExperimentsClient.common_organization_path) + parse_common_organization_path = staticmethod( + ExperimentsClient.parse_common_organization_path + ) + + common_project_path = staticmethod(ExperimentsClient.common_project_path) + parse_common_project_path = staticmethod( + ExperimentsClient.parse_common_project_path + ) + + common_location_path = staticmethod(ExperimentsClient.common_location_path) + parse_common_location_path = staticmethod( + ExperimentsClient.parse_common_location_path + ) + + from_service_account_file = ExperimentsClient.from_service_account_file + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ExperimentsTransport: + """Return the transport used by the client instance. + + Returns: + ExperimentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(ExperimentsClient).get_transport_class, type(ExperimentsClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, ExperimentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the experiments 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, ~.ExperimentsTransport]): 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 = ExperimentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_experiments( + self, + request: experiment.ListExperimentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExperimentsAsyncPager: + r"""Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`~.experiment.ListExperimentsRequest`): + The request object. The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + parent (:class:`str`): + Required. The + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to list all environments for. Format: + ``projects//locations//agents//environments/``. + 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: + ~.pagers.ListExperimentsAsyncPager: + The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = experiment.ListExperimentsRequest(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_experiments, + default_timeout=None, + 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.ListExperimentsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_experiment( + self, + request: experiment.GetExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (:class:`~.experiment.GetExperimentRequest`): + The request object. The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.GetExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = experiment.GetExperimentRequest(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_experiment, + default_timeout=None, + 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 create_experiment( + self, + request: gcdc_experiment.CreateExperimentRequest = None, + *, + parent: str = None, + experiment: gcdc_experiment.Experiment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Creates an + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in + the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`~.gcdc_experiment.CreateExperimentRequest`): + The request object. The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.CreateExperiment]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to + create an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + for. Format: + ``projects//locations//agents//environments/``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + experiment (:class:`~.gcdc_experiment.Experiment`): + Required. The experiment to create. + This corresponds to the ``experiment`` 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: + ~.gcdc_experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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, experiment]) + 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 = gcdc_experiment.CreateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if experiment is not None: + request.experiment = experiment + + # 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_experiment, + default_timeout=None, + 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 update_experiment( + self, + request: gcdc_experiment.UpdateExperimentRequest = None, + *, + experiment: gcdc_experiment.Experiment = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (:class:`~.gcdc_experiment.UpdateExperimentRequest`): + The request object. The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.UpdateExperiment]. + experiment (:class:`~.gcdc_experiment.Experiment`): + Required. The experiment to update. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. The mask to control which + fields get 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: + ~.gcdc_experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([experiment, 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 = gcdc_experiment.UpdateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if experiment is not None: + request.experiment = experiment + 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_experiment, + default_timeout=None, + 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( + (("experiment.name", request.experiment.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_experiment( + self, + request: experiment.DeleteExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (:class:`~.experiment.DeleteExperimentRequest`): + The request object. The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.DeleteExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = experiment.DeleteExperimentRequest(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.delete_experiment, + default_timeout=None, + 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. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def start_experiment( + self, + request: experiment.StartExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from PENDING to + RUNNING. + + Args: + request (:class:`~.experiment.StartExperimentRequest`): + The request object. The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StartExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to start. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = experiment.StartExperimentRequest(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.start_experiment, + default_timeout=None, + 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 stop_experiment( + self, + request: experiment.StopExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from RUNNING to + DONE. + + Args: + request (:class:`~.experiment.StopExperimentRequest`): + The request object. The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StopExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to stop. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = experiment.StopExperimentRequest(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.stop_experiment, + default_timeout=None, + 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 + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ExperimentsAsyncClient",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py new file mode 100644 index 00000000..c332dc33 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py @@ -0,0 +1,929 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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 + +from google.cloud.dialogflowcx_v3beta1.services.experiments import pagers +from google.cloud.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ExperimentsGrpcTransport +from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport + + +class ExperimentsClientMeta(type): + """Metaclass for the Experiments 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[ExperimentsTransport]] + _transport_registry["grpc"] = ExperimentsGrpcTransport + _transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ExperimentsTransport]: + """Return 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 ExperimentsClient(metaclass=ExperimentsClientMeta): + """Service for managing + [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ExperimentsTransport: + """Return the transport used by the client instance. + + Returns: + ExperimentsTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def experiment_path( + project: str, location: str, agent: str, environment: str, experiment: str, + ) -> str: + """Return a fully-qualified experiment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format( + project=project, + location=location, + agent=agent, + environment=environment, + experiment=experiment, + ) + + @staticmethod + def parse_experiment_path(path: str) -> Dict[str, str]: + """Parse a experiment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/experiments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def version_path( + project: str, location: str, agent: str, flow: str, version: str, + ) -> str: + """Return a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( + project=project, location=location, agent=agent, flow=flow, version=version, + ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str, str]: + """Parse a version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return 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: + """Return 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: + """Return 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: + """Return 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: + """Return 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 {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ExperimentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the experiments 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, ~.ExperimentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.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. + 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ExperimentsTransport): + # transport is a ExperimentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_experiments( + self, + request: experiment.ListExperimentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExperimentsPager: + r"""Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`~.experiment.ListExperimentsRequest`): + The request object. The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + parent (:class:`str`): + Required. The + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to list all environments for. Format: + ``projects//locations//agents//environments/``. + 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: + ~.pagers.ListExperimentsPager: + The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 experiment.ListExperimentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.ListExperimentsRequest): + request = experiment.ListExperimentsRequest(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_experiments] + + # 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.ListExperimentsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_experiment( + self, + request: experiment.GetExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (:class:`~.experiment.GetExperimentRequest`): + The request object. The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.GetExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 experiment.GetExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.GetExperimentRequest): + request = experiment.GetExperimentRequest(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_experiment] + + # 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 create_experiment( + self, + request: gcdc_experiment.CreateExperimentRequest = None, + *, + parent: str = None, + experiment: gcdc_experiment.Experiment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Creates an + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in + the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`~.gcdc_experiment.CreateExperimentRequest`): + The request object. The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.CreateExperiment]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to + create an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + for. Format: + ``projects//locations//agents//environments/``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + experiment (:class:`~.gcdc_experiment.Experiment`): + Required. The experiment to create. + This corresponds to the ``experiment`` 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: + ~.gcdc_experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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, experiment]) + 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 gcdc_experiment.CreateExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_experiment.CreateExperimentRequest): + request = gcdc_experiment.CreateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if experiment is not None: + request.experiment = experiment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_experiment] + + # 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 update_experiment( + self, + request: gcdc_experiment.UpdateExperimentRequest = None, + *, + experiment: gcdc_experiment.Experiment = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (:class:`~.gcdc_experiment.UpdateExperimentRequest`): + The request object. The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.UpdateExperiment]. + experiment (:class:`~.gcdc_experiment.Experiment`): + Required. The experiment to update. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. The mask to control which + fields get 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: + ~.gcdc_experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([experiment, 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 gcdc_experiment.UpdateExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_experiment.UpdateExperimentRequest): + request = gcdc_experiment.UpdateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if experiment is not None: + request.experiment = experiment + 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_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("experiment.name", request.experiment.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_experiment( + self, + request: experiment.DeleteExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (:class:`~.experiment.DeleteExperimentRequest`): + The request object. The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.DeleteExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 experiment.DeleteExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.DeleteExperimentRequest): + request = experiment.DeleteExperimentRequest(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.delete_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def start_experiment( + self, + request: experiment.StartExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from PENDING to + RUNNING. + + Args: + request (:class:`~.experiment.StartExperimentRequest`): + The request object. The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StartExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to start. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 experiment.StartExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.StartExperimentRequest): + request = experiment.StartExperimentRequest(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.start_experiment] + + # 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 stop_experiment( + self, + request: experiment.StopExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from RUNNING to + DONE. + + Args: + request (:class:`~.experiment.StopExperimentRequest`): + The request object. The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StopExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to stop. + Format: + ``projects//locations//agents//environments//experiments/``. + 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: + ~.experiment.Experiment: + Represents an experiment in an + environment. Next ID: 13 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 experiment.StopExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.StopExperimentRequest): + request = experiment.StopExperimentRequest(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.stop_experiment] + + # 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 + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ExperimentsClient",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py new file mode 100644 index 00000000..d01901a5 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.dialogflowcx_v3beta1.types import experiment + + +class ListExperimentsPager: + """A pager for iterating through ``list_experiments`` requests. + + This class thinly wraps an initial + :class:`~.experiment.ListExperimentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``experiments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExperiments`` requests and continue to iterate + through the ``experiments`` field on the + corresponding responses. + + All the usual :class:`~.experiment.ListExperimentsResponse` + 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[..., experiment.ListExperimentsResponse], + request: experiment.ListExperimentsRequest, + response: experiment.ListExperimentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.experiment.ListExperimentsRequest`): + The initial request object. + response (:class:`~.experiment.ListExperimentsResponse`): + 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 = experiment.ListExperimentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[experiment.ListExperimentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[experiment.Experiment]: + for page in self.pages: + yield from page.experiments + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListExperimentsAsyncPager: + """A pager for iterating through ``list_experiments`` requests. + + This class thinly wraps an initial + :class:`~.experiment.ListExperimentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``experiments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExperiments`` requests and continue to iterate + through the ``experiments`` field on the + corresponding responses. + + All the usual :class:`~.experiment.ListExperimentsResponse` + 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[experiment.ListExperimentsResponse]], + request: experiment.ListExperimentsRequest, + response: experiment.ListExperimentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.experiment.ListExperimentsRequest`): + The initial request object. + response (:class:`~.experiment.ListExperimentsResponse`): + 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 = experiment.ListExperimentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[experiment.ListExperimentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[experiment.Experiment]: + async def async_generator(): + async for page in self.pages: + for response in page.experiments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py new file mode 100644 index 00000000..d1972e23 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import ExperimentsTransport +from .grpc import ExperimentsGrpcTransport +from .grpc_asyncio import ExperimentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ExperimentsTransport]] +_transport_registry["grpc"] = ExperimentsGrpcTransport +_transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport + +__all__ = ( + "ExperimentsTransport", + "ExperimentsGrpcTransport", + "ExperimentsGrpcAsyncIOTransport", +) diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py new file mode 100644 index 00000000..6f98bde7 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ExperimentsTransport(abc.ABC): + """Abstract transport class for Experiments.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **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. + scope (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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_experiments: gapic_v1.method.wrap_method( + self.list_experiments, default_timeout=None, client_info=client_info, + ), + self.get_experiment: gapic_v1.method.wrap_method( + self.get_experiment, default_timeout=None, client_info=client_info, + ), + self.create_experiment: gapic_v1.method.wrap_method( + self.create_experiment, default_timeout=None, client_info=client_info, + ), + self.update_experiment: gapic_v1.method.wrap_method( + self.update_experiment, default_timeout=None, client_info=client_info, + ), + self.delete_experiment: gapic_v1.method.wrap_method( + self.delete_experiment, default_timeout=None, client_info=client_info, + ), + self.start_experiment: gapic_v1.method.wrap_method( + self.start_experiment, default_timeout=None, client_info=client_info, + ), + self.stop_experiment: gapic_v1.method.wrap_method( + self.stop_experiment, default_timeout=None, client_info=client_info, + ), + } + + @property + def list_experiments( + self, + ) -> typing.Callable[ + [experiment.ListExperimentsRequest], + typing.Union[ + experiment.ListExperimentsResponse, + typing.Awaitable[experiment.ListExperimentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_experiment( + self, + ) -> typing.Callable[ + [experiment.GetExperimentRequest], + typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + ]: + raise NotImplementedError() + + @property + def create_experiment( + self, + ) -> typing.Callable[ + [gcdc_experiment.CreateExperimentRequest], + typing.Union[ + gcdc_experiment.Experiment, typing.Awaitable[gcdc_experiment.Experiment] + ], + ]: + raise NotImplementedError() + + @property + def update_experiment( + self, + ) -> typing.Callable[ + [gcdc_experiment.UpdateExperimentRequest], + typing.Union[ + gcdc_experiment.Experiment, typing.Awaitable[gcdc_experiment.Experiment] + ], + ]: + raise NotImplementedError() + + @property + def delete_experiment( + self, + ) -> typing.Callable[ + [experiment.DeleteExperimentRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def start_experiment( + self, + ) -> typing.Callable[ + [experiment.StartExperimentRequest], + typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + ]: + raise NotImplementedError() + + @property + def stop_experiment( + self, + ) -> typing.Callable[ + [experiment.StopExperimentRequest], + typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + ]: + raise NotImplementedError() + + +__all__ = ("ExperimentsTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py new file mode 100644 index 00000000..ba506a12 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py @@ -0,0 +1,445 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO + + +class ExperimentsGrpcTransport(ExperimentsTransport): + """gRPC backend transport for Experiments. + + Service for managing + [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + 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 = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 applicatin 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 grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + 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._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_experiments( + self, + ) -> Callable[ + [experiment.ListExperimentsRequest], experiment.ListExperimentsResponse + ]: + r"""Return a callable for the list experiments method over gRPC. + + Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.ListExperimentsRequest], + ~.ListExperimentsResponse]: + 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_experiments" not in self._stubs: + self._stubs["list_experiments"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/ListExperiments", + request_serializer=experiment.ListExperimentsRequest.serialize, + response_deserializer=experiment.ListExperimentsResponse.deserialize, + ) + return self._stubs["list_experiments"] + + @property + def get_experiment( + self, + ) -> Callable[[experiment.GetExperimentRequest], experiment.Experiment]: + r"""Return a callable for the get experiment method over gRPC. + + Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.GetExperimentRequest], + ~.Experiment]: + 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_experiment" not in self._stubs: + self._stubs["get_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/GetExperiment", + request_serializer=experiment.GetExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["get_experiment"] + + @property + def create_experiment( + self, + ) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], gcdc_experiment.Experiment + ]: + r"""Return a callable for the create experiment method over gRPC. + + Creates an + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in + the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.CreateExperimentRequest], + ~.Experiment]: + 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_experiment" not in self._stubs: + self._stubs["create_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/CreateExperiment", + request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs["create_experiment"] + + @property + def update_experiment( + self, + ) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], gcdc_experiment.Experiment + ]: + r"""Return a callable for the update experiment method over gRPC. + + Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.UpdateExperimentRequest], + ~.Experiment]: + 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_experiment" not in self._stubs: + self._stubs["update_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/UpdateExperiment", + request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs["update_experiment"] + + @property + def delete_experiment( + self, + ) -> Callable[[experiment.DeleteExperimentRequest], empty.Empty]: + r"""Return a callable for the delete experiment method over gRPC. + + Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.DeleteExperimentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_experiment" not in self._stubs: + self._stubs["delete_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/DeleteExperiment", + request_serializer=experiment.DeleteExperimentRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_experiment"] + + @property + def start_experiment( + self, + ) -> Callable[[experiment.StartExperimentRequest], experiment.Experiment]: + r"""Return a callable for the start experiment method over gRPC. + + Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from PENDING to + RUNNING. + + Returns: + Callable[[~.StartExperimentRequest], + ~.Experiment]: + 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 "start_experiment" not in self._stubs: + self._stubs["start_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/StartExperiment", + request_serializer=experiment.StartExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["start_experiment"] + + @property + def stop_experiment( + self, + ) -> Callable[[experiment.StopExperimentRequest], experiment.Experiment]: + r"""Return a callable for the stop experiment method over gRPC. + + Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from RUNNING to + DONE. + + Returns: + Callable[[~.StopExperimentRequest], + ~.Experiment]: + 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 "stop_experiment" not in self._stubs: + self._stubs["stop_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/StopExperiment", + request_serializer=experiment.StopExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["stop_experiment"] + + +__all__ = ("ExperimentsGrpcTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py new file mode 100644 index 00000000..3950a0d0 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py @@ -0,0 +1,452 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import 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.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .grpc import ExperimentsGrpcTransport + + +class ExperimentsGrpcAsyncIOTransport(ExperimentsTransport): + """gRPC AsyncIO backend transport for Experiments. + + Service for managing + [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + 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 = "dialogflow.googleapis.com", + credentials: 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: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 applicatin 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 grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + 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._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_experiments( + self, + ) -> Callable[ + [experiment.ListExperimentsRequest], + Awaitable[experiment.ListExperimentsResponse], + ]: + r"""Return a callable for the list experiments method over gRPC. + + Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.ListExperimentsRequest], + Awaitable[~.ListExperimentsResponse]]: + 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_experiments" not in self._stubs: + self._stubs["list_experiments"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/ListExperiments", + request_serializer=experiment.ListExperimentsRequest.serialize, + response_deserializer=experiment.ListExperimentsResponse.deserialize, + ) + return self._stubs["list_experiments"] + + @property + def get_experiment( + self, + ) -> Callable[[experiment.GetExperimentRequest], Awaitable[experiment.Experiment]]: + r"""Return a callable for the get experiment method over gRPC. + + Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.GetExperimentRequest], + Awaitable[~.Experiment]]: + 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_experiment" not in self._stubs: + self._stubs["get_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/GetExperiment", + request_serializer=experiment.GetExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["get_experiment"] + + @property + def create_experiment( + self, + ) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], Awaitable[gcdc_experiment.Experiment] + ]: + r"""Return a callable for the create experiment method over gRPC. + + Creates an + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in + the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.CreateExperimentRequest], + Awaitable[~.Experiment]]: + 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_experiment" not in self._stubs: + self._stubs["create_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/CreateExperiment", + request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs["create_experiment"] + + @property + def update_experiment( + self, + ) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], Awaitable[gcdc_experiment.Experiment] + ]: + r"""Return a callable for the update experiment method over gRPC. + + Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.UpdateExperimentRequest], + Awaitable[~.Experiment]]: + 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_experiment" not in self._stubs: + self._stubs["update_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/UpdateExperiment", + request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs["update_experiment"] + + @property + def delete_experiment( + self, + ) -> Callable[[experiment.DeleteExperimentRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete experiment method over gRPC. + + Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.DeleteExperimentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_experiment" not in self._stubs: + self._stubs["delete_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/DeleteExperiment", + request_serializer=experiment.DeleteExperimentRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_experiment"] + + @property + def start_experiment( + self, + ) -> Callable[ + [experiment.StartExperimentRequest], Awaitable[experiment.Experiment] + ]: + r"""Return a callable for the start experiment method over gRPC. + + Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from PENDING to + RUNNING. + + Returns: + Callable[[~.StartExperimentRequest], + Awaitable[~.Experiment]]: + 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 "start_experiment" not in self._stubs: + self._stubs["start_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/StartExperiment", + request_serializer=experiment.StartExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["start_experiment"] + + @property + def stop_experiment( + self, + ) -> Callable[[experiment.StopExperimentRequest], Awaitable[experiment.Experiment]]: + r"""Return a callable for the stop experiment method over gRPC. + + Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from RUNNING to + DONE. + + Returns: + Callable[[~.StopExperimentRequest], + Awaitable[~.Experiment]]: + 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 "stop_experiment" not in self._stubs: + self._stubs["stop_experiment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Experiments/StopExperiment", + request_serializer=experiment.StopExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs["stop_experiment"] + + +__all__ = ("ExperimentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py new file mode 100644 index 00000000..66f0a799 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import SecuritySettingsServiceClient +from .async_client import SecuritySettingsServiceAsyncClient + +__all__ = ( + "SecuritySettingsServiceClient", + "SecuritySettingsServiceAsyncClient", +) diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py new file mode 100644 index 00000000..537126f5 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py @@ -0,0 +1,572 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import ( + security_settings as gcdc_security_settings, +) +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + +from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport +from .client import SecuritySettingsServiceClient + + +class SecuritySettingsServiceAsyncClient: + """Service for managing security settings for Dialogflow.""" + + _client: SecuritySettingsServiceClient + + DEFAULT_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_MTLS_ENDPOINT + + security_settings_path = staticmethod( + SecuritySettingsServiceClient.security_settings_path + ) + parse_security_settings_path = staticmethod( + SecuritySettingsServiceClient.parse_security_settings_path + ) + + common_billing_account_path = staticmethod( + SecuritySettingsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SecuritySettingsServiceClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(SecuritySettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SecuritySettingsServiceClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + SecuritySettingsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SecuritySettingsServiceClient.parse_common_organization_path + ) + + common_project_path = staticmethod( + SecuritySettingsServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + SecuritySettingsServiceClient.parse_common_project_path + ) + + common_location_path = staticmethod( + SecuritySettingsServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + SecuritySettingsServiceClient.parse_common_location_path + ) + + from_service_account_file = SecuritySettingsServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SecuritySettingsServiceTransport: + """Return the transport used by the client instance. + + Returns: + SecuritySettingsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(SecuritySettingsServiceClient).get_transport_class, + type(SecuritySettingsServiceClient), + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecuritySettingsServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the security settings 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, ~.SecuritySettingsServiceTransport]): 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 = SecuritySettingsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def create_security_settings( + self, + request: gcdc_security_settings.CreateSecuritySettingsRequest = None, + *, + parent: str = None, + security_settings: gcdc_security_settings.SecuritySettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Create security settings in the specified location. + + Args: + request (:class:`~.gcdc_security_settings.CreateSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.CreateSecuritySettings][]. + parent (:class:`str`): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + for. Format: + ``projects//locations/``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_settings (:class:`~.gcdc_security_settings.SecuritySettings`): + Required. The security settings to + create. + This corresponds to the ``security_settings`` 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: + ~.gcdc_security_settings.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, security_settings]) + 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 = gcdc_security_settings.CreateSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if security_settings is not None: + request.security_settings = security_settings + + # 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_security_settings, + default_timeout=None, + 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 get_security_settings( + self, + request: security_settings.GetSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_settings.SecuritySettings: + r"""Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Args: + request (:class:`~.security_settings.GetSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.GetSecuritySettings]. + name (:class:`str`): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + 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: + ~.security_settings.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = security_settings.GetSecuritySettingsRequest(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_security_settings, + default_timeout=None, + 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_security_settings( + self, + request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, + *, + security_settings: gcdc_security_settings.SecuritySettings = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Args: + request (:class:`~.gcdc_security_settings.UpdateSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings]. + security_settings (:class:`~.gcdc_security_settings.SecuritySettings`): + Required. [SecuritySettings] object that contains values + for each of the fields to update. + This corresponds to the ``security_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will 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: + ~.gcdc_security_settings.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_settings, 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 = gcdc_security_settings.UpdateSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if security_settings is not None: + request.security_settings = security_settings + 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_security_settings, + default_timeout=None, + 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( + (("security_settings.name", request.security_settings.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_security_settings( + self, + request: security_settings.ListSecuritySettingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecuritySettingsAsyncPager: + r"""Returns the list of all security settings in the + specified location. + + Args: + request (:class:`~.security_settings.ListSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.ListSecuritySettings][]. + parent (:class:`str`): + Required. The location to list all security settings + for. Format: + ``projects//locations/``. + 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: + ~.pagers.ListSecuritySettingsAsyncPager: + The response message for + [SecuritySettings.ListSecuritySettings][]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = security_settings.ListSecuritySettingsRequest(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_security_settings, + default_timeout=None, + 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.ListSecuritySettingsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_security_settings( + self, + request: security_settings.DeleteSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Args: + request (:class:`~.security_settings.DeleteSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.DeleteSecuritySettings][]. + name (:class:`str`): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = security_settings.DeleteSecuritySettingsRequest(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.delete_security_settings, + default_timeout=None, + 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. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecuritySettingsServiceAsyncClient",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py new file mode 100644 index 00000000..a425d7e7 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py @@ -0,0 +1,767 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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 + +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import ( + security_settings as gcdc_security_settings, +) +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + +from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecuritySettingsServiceGrpcTransport +from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport + + +class SecuritySettingsServiceClientMeta(type): + """Metaclass for the SecuritySettingsService 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[SecuritySettingsServiceTransport]] + _transport_registry["grpc"] = SecuritySettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SecuritySettingsServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[SecuritySettingsServiceTransport]: + """Return 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 SecuritySettingsServiceClient(metaclass=SecuritySettingsServiceClientMeta): + """Service for managing security settings for Dialogflow.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SecuritySettingsServiceTransport: + """Return the transport used by the client instance. + + Returns: + SecuritySettingsServiceTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def security_settings_path( + project: str, location: str, security_settings: str, + ) -> str: + """Return a fully-qualified security_settings string.""" + return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( + project=project, location=location, security_settings=security_settings, + ) + + @staticmethod + def parse_security_settings_path(path: str) -> Dict[str, str]: + """Parse a security_settings path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return 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: + """Return 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: + """Return 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: + """Return 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: + """Return 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 {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, SecuritySettingsServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the security settings 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, ~.SecuritySettingsServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.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. + 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SecuritySettingsServiceTransport): + # transport is a SecuritySettingsServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_security_settings( + self, + request: gcdc_security_settings.CreateSecuritySettingsRequest = None, + *, + parent: str = None, + security_settings: gcdc_security_settings.SecuritySettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Create security settings in the specified location. + + Args: + request (:class:`~.gcdc_security_settings.CreateSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.CreateSecuritySettings][]. + parent (:class:`str`): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + for. Format: + ``projects//locations/``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_settings (:class:`~.gcdc_security_settings.SecuritySettings`): + Required. The security settings to + create. + This corresponds to the ``security_settings`` 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: + ~.gcdc_security_settings.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, security_settings]) + 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 gcdc_security_settings.CreateSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, gcdc_security_settings.CreateSecuritySettingsRequest + ): + request = gcdc_security_settings.CreateSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if security_settings is not None: + request.security_settings = security_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_security_settings] + + # 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 get_security_settings( + self, + request: security_settings.GetSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_settings.SecuritySettings: + r"""Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Args: + request (:class:`~.security_settings.GetSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.GetSecuritySettings]. + name (:class:`str`): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + 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: + ~.security_settings.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 security_settings.GetSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.GetSecuritySettingsRequest): + request = security_settings.GetSecuritySettingsRequest(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_security_settings] + + # 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_security_settings( + self, + request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, + *, + security_settings: gcdc_security_settings.SecuritySettings = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Args: + request (:class:`~.gcdc_security_settings.UpdateSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings]. + security_settings (:class:`~.gcdc_security_settings.SecuritySettings`): + Required. [SecuritySettings] object that contains values + for each of the fields to update. + This corresponds to the ``security_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will 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: + ~.gcdc_security_settings.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_settings, 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 gcdc_security_settings.UpdateSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, gcdc_security_settings.UpdateSecuritySettingsRequest + ): + request = gcdc_security_settings.UpdateSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if security_settings is not None: + request.security_settings = security_settings + 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_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_settings.name", request.security_settings.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_security_settings( + self, + request: security_settings.ListSecuritySettingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecuritySettingsPager: + r"""Returns the list of all security settings in the + specified location. + + Args: + request (:class:`~.security_settings.ListSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.ListSecuritySettings][]. + parent (:class:`str`): + Required. The location to list all security settings + for. Format: + ``projects//locations/``. + 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: + ~.pagers.ListSecuritySettingsPager: + The response message for + [SecuritySettings.ListSecuritySettings][]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 security_settings.ListSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.ListSecuritySettingsRequest): + request = security_settings.ListSecuritySettingsRequest(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_security_settings] + + # 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.ListSecuritySettingsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_security_settings( + self, + request: security_settings.DeleteSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Args: + request (:class:`~.security_settings.DeleteSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.DeleteSecuritySettings][]. + name (:class:`str`): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + 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. + """ + # Create or coerce a protobuf request object. + # Sanity 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 security_settings.DeleteSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.DeleteSecuritySettingsRequest): + request = security_settings.DeleteSecuritySettingsRequest(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.delete_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecuritySettingsServiceClient",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py new file mode 100644 index 00000000..c8de228c --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.dialogflowcx_v3beta1.types import security_settings + + +class ListSecuritySettingsPager: + """A pager for iterating through ``list_security_settings`` requests. + + This class thinly wraps an initial + :class:`~.security_settings.ListSecuritySettingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``security_settings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecuritySettings`` requests and continue to iterate + through the ``security_settings`` field on the + corresponding responses. + + All the usual :class:`~.security_settings.ListSecuritySettingsResponse` + 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[..., security_settings.ListSecuritySettingsResponse], + request: security_settings.ListSecuritySettingsRequest, + response: security_settings.ListSecuritySettingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.security_settings.ListSecuritySettingsRequest`): + The initial request object. + response (:class:`~.security_settings.ListSecuritySettingsResponse`): + 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 = security_settings.ListSecuritySettingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[security_settings.ListSecuritySettingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[security_settings.SecuritySettings]: + for page in self.pages: + yield from page.security_settings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSecuritySettingsAsyncPager: + """A pager for iterating through ``list_security_settings`` requests. + + This class thinly wraps an initial + :class:`~.security_settings.ListSecuritySettingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``security_settings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecuritySettings`` requests and continue to iterate + through the ``security_settings`` field on the + corresponding responses. + + All the usual :class:`~.security_settings.ListSecuritySettingsResponse` + 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[security_settings.ListSecuritySettingsResponse] + ], + request: security_settings.ListSecuritySettingsRequest, + response: security_settings.ListSecuritySettingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.security_settings.ListSecuritySettingsRequest`): + The initial request object. + response (:class:`~.security_settings.ListSecuritySettingsResponse`): + 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 = security_settings.ListSecuritySettingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[security_settings.ListSecuritySettingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[security_settings.SecuritySettings]: + async def async_generator(): + async for page in self.pages: + for response in page.security_settings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py new file mode 100644 index 00000000..fc2aea1c --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import SecuritySettingsServiceTransport +from .grpc import SecuritySettingsServiceGrpcTransport +from .grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[SecuritySettingsServiceTransport]] +_transport_registry["grpc"] = SecuritySettingsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SecuritySettingsServiceGrpcAsyncIOTransport + +__all__ = ( + "SecuritySettingsServiceTransport", + "SecuritySettingsServiceGrpcTransport", + "SecuritySettingsServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py new file mode 100644 index 00000000..400fd363 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import ( + security_settings as gcdc_security_settings, +) +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SecuritySettingsServiceTransport(abc.ABC): + """Abstract transport class for SecuritySettingsService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **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. + scope (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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_security_settings: gapic_v1.method.wrap_method( + self.create_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_security_settings: gapic_v1.method.wrap_method( + self.get_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_security_settings: gapic_v1.method.wrap_method( + self.update_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.list_security_settings: gapic_v1.method.wrap_method( + self.list_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.delete_security_settings: gapic_v1.method.wrap_method( + self.delete_security_settings, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def create_security_settings( + self, + ) -> typing.Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + typing.Union[ + gcdc_security_settings.SecuritySettings, + typing.Awaitable[gcdc_security_settings.SecuritySettings], + ], + ]: + raise NotImplementedError() + + @property + def get_security_settings( + self, + ) -> typing.Callable[ + [security_settings.GetSecuritySettingsRequest], + typing.Union[ + security_settings.SecuritySettings, + typing.Awaitable[security_settings.SecuritySettings], + ], + ]: + raise NotImplementedError() + + @property + def update_security_settings( + self, + ) -> typing.Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + typing.Union[ + gcdc_security_settings.SecuritySettings, + typing.Awaitable[gcdc_security_settings.SecuritySettings], + ], + ]: + raise NotImplementedError() + + @property + def list_security_settings( + self, + ) -> typing.Callable[ + [security_settings.ListSecuritySettingsRequest], + typing.Union[ + security_settings.ListSecuritySettingsResponse, + typing.Awaitable[security_settings.ListSecuritySettingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_security_settings( + self, + ) -> typing.Callable[ + [security_settings.DeleteSecuritySettingsRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + +__all__ = ("SecuritySettingsServiceTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py new file mode 100644 index 00000000..3faaeb17 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py @@ -0,0 +1,392 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import ( + security_settings as gcdc_security_settings, +) +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO + + +class SecuritySettingsServiceGrpcTransport(SecuritySettingsServiceTransport): + """gRPC backend transport for SecuritySettingsService. + + Service for managing security settings for Dialogflow. + + 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 = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 applicatin 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 grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + 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._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_security_settings( + self, + ) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + gcdc_security_settings.SecuritySettings, + ]: + r"""Return a callable for the create security settings method over gRPC. + + Create security settings in the specified location. + + Returns: + Callable[[~.CreateSecuritySettingsRequest], + ~.SecuritySettings]: + 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_security_settings" not in self._stubs: + self._stubs["create_security_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/CreateSecuritySettings", + request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs["create_security_settings"] + + @property + def get_security_settings( + self, + ) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + security_settings.SecuritySettings, + ]: + r"""Return a callable for the get security settings method over gRPC. + + Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Returns: + Callable[[~.GetSecuritySettingsRequest], + ~.SecuritySettings]: + 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_security_settings" not in self._stubs: + self._stubs["get_security_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/GetSecuritySettings", + request_serializer=security_settings.GetSecuritySettingsRequest.serialize, + response_deserializer=security_settings.SecuritySettings.deserialize, + ) + return self._stubs["get_security_settings"] + + @property + def update_security_settings( + self, + ) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + gcdc_security_settings.SecuritySettings, + ]: + r"""Return a callable for the update security settings method over gRPC. + + Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Returns: + Callable[[~.UpdateSecuritySettingsRequest], + ~.SecuritySettings]: + 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_security_settings" not in self._stubs: + self._stubs["update_security_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/UpdateSecuritySettings", + request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs["update_security_settings"] + + @property + def list_security_settings( + self, + ) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + security_settings.ListSecuritySettingsResponse, + ]: + r"""Return a callable for the list security settings method over gRPC. + + Returns the list of all security settings in the + specified location. + + Returns: + Callable[[~.ListSecuritySettingsRequest], + ~.ListSecuritySettingsResponse]: + 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_security_settings" not in self._stubs: + self._stubs["list_security_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/ListSecuritySettings", + request_serializer=security_settings.ListSecuritySettingsRequest.serialize, + response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, + ) + return self._stubs["list_security_settings"] + + @property + def delete_security_settings( + self, + ) -> Callable[[security_settings.DeleteSecuritySettingsRequest], empty.Empty]: + r"""Return a callable for the delete security settings method over gRPC. + + Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Returns: + Callable[[~.DeleteSecuritySettingsRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_security_settings" not in self._stubs: + self._stubs["delete_security_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/DeleteSecuritySettings", + request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_security_settings"] + + +__all__ = ("SecuritySettingsServiceGrpcTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..921e1eec --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,398 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import 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.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import ( + security_settings as gcdc_security_settings, +) +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SecuritySettingsServiceGrpcTransport + + +class SecuritySettingsServiceGrpcAsyncIOTransport(SecuritySettingsServiceTransport): + """gRPC AsyncIO backend transport for SecuritySettingsService. + + Service for managing security settings for Dialogflow. + + 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 = "dialogflow.googleapis.com", + credentials: 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: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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 applicatin 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 grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + 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._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_security_settings( + self, + ) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + Awaitable[gcdc_security_settings.SecuritySettings], + ]: + r"""Return a callable for the create security settings method over gRPC. + + Create security settings in the specified location. + + Returns: + Callable[[~.CreateSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + 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_security_settings" not in self._stubs: + self._stubs["create_security_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/CreateSecuritySettings", + request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs["create_security_settings"] + + @property + def get_security_settings( + self, + ) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + Awaitable[security_settings.SecuritySettings], + ]: + r"""Return a callable for the get security settings method over gRPC. + + Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Returns: + Callable[[~.GetSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + 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_security_settings" not in self._stubs: + self._stubs["get_security_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/GetSecuritySettings", + request_serializer=security_settings.GetSecuritySettingsRequest.serialize, + response_deserializer=security_settings.SecuritySettings.deserialize, + ) + return self._stubs["get_security_settings"] + + @property + def update_security_settings( + self, + ) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + Awaitable[gcdc_security_settings.SecuritySettings], + ]: + r"""Return a callable for the update security settings method over gRPC. + + Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Returns: + Callable[[~.UpdateSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + 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_security_settings" not in self._stubs: + self._stubs["update_security_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/UpdateSecuritySettings", + request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs["update_security_settings"] + + @property + def list_security_settings( + self, + ) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + Awaitable[security_settings.ListSecuritySettingsResponse], + ]: + r"""Return a callable for the list security settings method over gRPC. + + Returns the list of all security settings in the + specified location. + + Returns: + Callable[[~.ListSecuritySettingsRequest], + Awaitable[~.ListSecuritySettingsResponse]]: + 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_security_settings" not in self._stubs: + self._stubs["list_security_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/ListSecuritySettings", + request_serializer=security_settings.ListSecuritySettingsRequest.serialize, + response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, + ) + return self._stubs["list_security_settings"] + + @property + def delete_security_settings( + self, + ) -> Callable[ + [security_settings.DeleteSecuritySettingsRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete security settings method over gRPC. + + Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Returns: + Callable[[~.DeleteSecuritySettingsRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_security_settings" not in self._stubs: + self._stubs["delete_security_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/DeleteSecuritySettings", + request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_security_settings"] + + +__all__ = ("SecuritySettingsServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/types/__init__.py b/google/cloud/dialogflowcx_v3beta1/types/__init__.py index b4e37de5..248e71eb 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/types/__init__.py @@ -40,6 +40,15 @@ UpdateFlowRequest, TrainFlowRequest, ) +from .security_settings import ( + GetSecuritySettingsRequest, + UpdateSecuritySettingsRequest, + ListSecuritySettingsRequest, + ListSecuritySettingsResponse, + CreateSecuritySettingsRequest, + DeleteSecuritySettingsRequest, + SecuritySettings, +) from .agent import ( SpeechToTextSettings, Agent, @@ -84,6 +93,19 @@ LookupEnvironmentHistoryRequest, LookupEnvironmentHistoryResponse, ) +from .experiment import ( + Experiment, + VersionVariants, + VariantsHistory, + ListExperimentsRequest, + ListExperimentsResponse, + GetExperimentRequest, + CreateExperimentRequest, + UpdateExperimentRequest, + DeleteExperimentRequest, + StartExperimentRequest, + StopExperimentRequest, +) from .intent import ( Intent, ListIntentsRequest, @@ -180,6 +202,13 @@ "GetFlowRequest", "UpdateFlowRequest", "TrainFlowRequest", + "GetSecuritySettingsRequest", + "UpdateSecuritySettingsRequest", + "ListSecuritySettingsRequest", + "ListSecuritySettingsResponse", + "CreateSecuritySettingsRequest", + "DeleteSecuritySettingsRequest", + "SecuritySettings", "SpeechToTextSettings", "Agent", "ListAgentsRequest", @@ -216,6 +245,17 @@ "DeleteEnvironmentRequest", "LookupEnvironmentHistoryRequest", "LookupEnvironmentHistoryResponse", + "Experiment", + "VersionVariants", + "VariantsHistory", + "ListExperimentsRequest", + "ListExperimentsResponse", + "GetExperimentRequest", + "CreateExperimentRequest", + "UpdateExperimentRequest", + "DeleteExperimentRequest", + "StartExperimentRequest", + "StopExperimentRequest", "Intent", "ListIntentsRequest", "ListIntentsResponse", diff --git a/google/cloud/dialogflowcx_v3beta1/types/experiment.py b/google/cloud/dialogflowcx_v3beta1/types/experiment.py new file mode 100644 index 00000000..3e1e0e6f --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/types/experiment.py @@ -0,0 +1,445 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3beta1", + manifest={ + "Experiment", + "VersionVariants", + "VariantsHistory", + "ListExperimentsRequest", + "ListExperimentsResponse", + "GetExperimentRequest", + "CreateExperimentRequest", + "UpdateExperimentRequest", + "DeleteExperimentRequest", + "StartExperimentRequest", + "StopExperimentRequest", + }, +) + + +class Experiment(proto.Message): + r"""Represents an experiment in an environment. + Next ID: 13 + + Attributes: + name (str): + The name of the experiment. + Format: projects//locations//agents//environments//experiments/.. + display_name (str): + Required. The human-readable name of the + experiment (unique in an environment). Limit of + 64 characters. + description (str): + The human-readable description of the + experiment. + state (~.gcdc_experiment.Experiment.State): + The current state of the experiment. + Transition triggered by + Expriments.StartExperiment: PENDING->RUNNING. + Transition triggered by + Expriments.CancelExperiment: PENDING->CANCELLED + or RUNNING->CANCELLED. + definition (~.gcdc_experiment.Experiment.Definition): + The definition of the experiment. + result (~.gcdc_experiment.Experiment.Result): + Inference result of the experiment. + create_time (~.timestamp.Timestamp): + Creation time of this experiment. + start_time (~.timestamp.Timestamp): + Start time of this experiment. + end_time (~.timestamp.Timestamp): + End time of this experiment. + last_update_time (~.timestamp.Timestamp): + Last update time of this experiment. + experiment_length (~.duration.Duration): + Maximum number of days to run the experiment. + variants_history (Sequence[~.gcdc_experiment.VariantsHistory]): + The history of updates to the experiment + variants. + """ + + class State(proto.Enum): + r"""The state of the experiment.""" + STATE_UNSPECIFIED = 0 + DRAFT = 1 + RUNNING = 2 + DONE = 3 + + class Definition(proto.Message): + r"""Definition of the experiment. + Next ID: 3 + + Attributes: + condition (str): + The condition defines which subset of sessions are selected + for this experiment. If not specified, all sessions are + eligible. E.g. "query_input.language_code=en" See the + `conditions + reference `__. + version_variants (~.gcdc_experiment.VersionVariants): + The flow versions as the variants of this + experiment. + """ + + condition = proto.Field(proto.STRING, number=1) + + version_variants = proto.Field( + proto.MESSAGE, number=2, oneof="variants", message="VersionVariants", + ) + + class Result(proto.Message): + r"""The inference result which includes an objective metric to + optimize and the confidence interval. + + Attributes: + version_metrics (Sequence[~.gcdc_experiment.Experiment.Result.VersionMetrics]): + Version variants and metrics. + last_update_time (~.timestamp.Timestamp): + The last time the experiment's stats data was + updated. Will have default value if stats have + never been computed for this experiment. + """ + + class MetricType(proto.Enum): + r"""Types of metric for Dialogflow experiment.""" + METRIC_UNSPECIFIED = 0 + CONTAINED_SESSION_NO_CALLBACK_RATE = 1 + LIVE_AGENT_HANDOFF_RATE = 2 + CALLBACK_SESSION_RATE = 3 + ABANDONED_SESSION_RATE = 4 + SESSION_END_RATE = 5 + + class ConfidenceInterval(proto.Message): + r"""A confidence interval is a range of possible values for the + experiment objective you are trying to measure. + + Attributes: + confidence_level (float): + The confidence level used to construct the + interval, i.e. there is X% chance that the true + value is within this interval. + ratio (float): + The percent change between an experiment + metric's value and the value for its control. + lower_bound (float): + Lower bound of the interval. + upper_bound (float): + Upper bound of the interval. + """ + + confidence_level = proto.Field(proto.DOUBLE, number=1) + + ratio = proto.Field(proto.DOUBLE, number=2) + + lower_bound = proto.Field(proto.DOUBLE, number=3) + + upper_bound = proto.Field(proto.DOUBLE, number=4) + + class Metric(proto.Message): + r"""Metric and corresponding confidence intervals. + + Attributes: + type_ (~.gcdc_experiment.Experiment.Result.MetricType): + The type of the metric. + ratio (float): + Ratio value of a metric. + confidence_interval (~.gcdc_experiment.Experiment.Result.ConfidenceInterval): + The probability that the treatment is better + than all other treatments in the experiment + """ + + type_ = proto.Field( + proto.ENUM, number=1, enum="Experiment.Result.MetricType", + ) + + ratio = proto.Field(proto.DOUBLE, number=2, oneof="value") + + confidence_interval = proto.Field( + proto.MESSAGE, number=3, message="Experiment.Result.ConfidenceInterval", + ) + + class VersionMetrics(proto.Message): + r"""Version variant and associated metrics. + + Attributes: + version (str): + The name of the flow + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + Format: + ``projects//locations//agents//flows//versions/``. + metrics (Sequence[~.gcdc_experiment.Experiment.Result.Metric]): + The metrics and corresponding confidence + intervals in the inference result. + session_count (int): + Number of sessions that were allocated to + this version. + """ + + version = proto.Field(proto.STRING, number=1) + + metrics = proto.RepeatedField( + proto.MESSAGE, number=2, message="Experiment.Result.Metric", + ) + + session_count = proto.Field(proto.INT32, number=3) + + version_metrics = proto.RepeatedField( + proto.MESSAGE, number=1, message="Experiment.Result.VersionMetrics", + ) + + last_update_time = proto.Field( + proto.MESSAGE, number=2, message=timestamp.Timestamp, + ) + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + state = proto.Field(proto.ENUM, number=4, enum=State,) + + definition = proto.Field(proto.MESSAGE, number=5, message=Definition,) + + result = proto.Field(proto.MESSAGE, number=6, message=Result,) + + create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) + + start_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + last_update_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp.Timestamp, + ) + + experiment_length = proto.Field( + proto.MESSAGE, number=11, message=duration.Duration, + ) + + variants_history = proto.RepeatedField( + proto.MESSAGE, number=12, message="VariantsHistory", + ) + + +class VersionVariants(proto.Message): + r"""A list of flow version variants. + + Attributes: + variants (Sequence[~.gcdc_experiment.VersionVariants.Variant]): + A list of flow version variants. + """ + + class Variant(proto.Message): + r"""A single flow version with specified traffic allocation. + + Attributes: + version (str): + The name of the flow version. Format: + ``projects//locations//agents//flows//versions/``. + traffic_allocation (float): + Percentage of the traffic which should be + routed to this version of flow. Traffic + allocation for a single flow must sum up to 1.0. + is_control_group (bool): + Whether the variant is for the control group. + """ + + version = proto.Field(proto.STRING, number=1) + + traffic_allocation = proto.Field(proto.FLOAT, number=2) + + is_control_group = proto.Field(proto.BOOL, number=3) + + variants = proto.RepeatedField(proto.MESSAGE, number=1, message=Variant,) + + +class VariantsHistory(proto.Message): + r"""The history of variants update. + + Attributes: + version_variants (~.gcdc_experiment.VersionVariants): + The flow versions as the variants. + update_time (~.timestamp.Timestamp): + Update time of the variants. + """ + + version_variants = proto.Field( + proto.MESSAGE, number=1, oneof="variants", message="VersionVariants", + ) + + update_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + +class ListExperimentsRequest(proto.Message): + r"""The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + + Attributes: + parent (str): + Required. The + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to list all environments for. Format: + ``projects//locations//agents//environments/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListExperimentsResponse(proto.Message): + r"""The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + + Attributes: + experiments (Sequence[~.gcdc_experiment.Experiment]): + The list of experiments. There will be a maximum number of + items returned based on the page_size field in the request. + The list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + experiments = proto.RepeatedField(proto.MESSAGE, number=1, message="Experiment",) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetExperimentRequest(proto.Message): + r"""The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.GetExperiment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateExperimentRequest(proto.Message): + r"""The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.CreateExperiment]. + + Attributes: + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + for. Format: + ``projects//locations//agents//environments/``. + experiment (~.gcdc_experiment.Experiment): + Required. The experiment to create. + """ + + parent = proto.Field(proto.STRING, number=1) + + experiment = proto.Field(proto.MESSAGE, number=2, message="Experiment",) + + +class UpdateExperimentRequest(proto.Message): + r"""The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.UpdateExperiment]. + + Attributes: + experiment (~.gcdc_experiment.Experiment): + Required. The experiment to update. + update_mask (~.field_mask.FieldMask): + Required. The mask to control which fields + get updated. + """ + + experiment = proto.Field(proto.MESSAGE, number=1, message="Experiment",) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteExperimentRequest(proto.Message): + r"""The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.DeleteExperiment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class StartExperimentRequest(proto.Message): + r"""The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StartExperiment]. + + Attributes: + name (str): + Required. Resource name of the experiment to start. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class StopExperimentRequest(proto.Message): + r"""The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StopExperiment]. + + Attributes: + name (str): + Required. Resource name of the experiment to stop. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field(proto.STRING, number=1) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/response_message.py b/google/cloud/dialogflowcx_v3beta1/types/response_message.py index 72a21517..ad0e2726 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/response_message.py +++ b/google/cloud/dialogflowcx_v3beta1/types/response_message.py @@ -180,32 +180,6 @@ class OutputAudioText(proto.Message): allow_playback_interruption = proto.Field(proto.BOOL, number=3) - class PlayAudio(proto.Message): - r"""Specifies an audio clip to be played by the client as part of - the response. - - Attributes: - audio_uri (str): - Required. URI of the audio clip. Dialogflow - does not impose any validation on this value. It - is specific to the client that reads it. - allow_playback_interruption (bool): - Output only. Whether the playback of this - message can be interrupted by the end user's - speech and the client can then starts the next - Dialogflow request. - """ - - audio_uri = proto.Field(proto.STRING, number=1) - - allow_playback_interruption = proto.Field(proto.BOOL, number=2) - - class EndInteraction(proto.Message): - r"""Indicates that interaction with the Dialogflow agent has - ended. This message is generated by Dialogflow only and not - supposed to be defined by the user. - """ - class MixedAudio(proto.Message): r"""Represents an audio message that is composed of both segments synthesized from the Dialogflow agent prompts and ones hosted @@ -249,6 +223,32 @@ class Segment(proto.Message): proto.MESSAGE, number=1, message="ResponseMessage.MixedAudio.Segment", ) + class EndInteraction(proto.Message): + r"""Indicates that interaction with the Dialogflow agent has + ended. This message is generated by Dialogflow only and not + supposed to be defined by the user. + """ + + class PlayAudio(proto.Message): + r"""Specifies an audio clip to be played by the client as part of + the response. + + Attributes: + audio_uri (str): + Required. URI of the audio clip. Dialogflow + does not impose any validation on this value. It + is specific to the client that reads it. + allow_playback_interruption (bool): + Output only. Whether the playback of this + message can be interrupted by the end user's + speech and the client can then starts the next + Dialogflow request. + """ + + audio_uri = proto.Field(proto.STRING, number=1) + + allow_playback_interruption = proto.Field(proto.BOOL, number=2) + text = proto.Field(proto.MESSAGE, number=1, oneof="message", message=Text,) payload = proto.Field( diff --git a/google/cloud/dialogflowcx_v3beta1/types/security_settings.py b/google/cloud/dialogflowcx_v3beta1/types/security_settings.py new file mode 100644 index 00000000..41d00dbf --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/types/security_settings.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3beta1", + manifest={ + "GetSecuritySettingsRequest", + "UpdateSecuritySettingsRequest", + "ListSecuritySettingsRequest", + "ListSecuritySettingsResponse", + "CreateSecuritySettingsRequest", + "DeleteSecuritySettingsRequest", + "SecuritySettings", + }, +) + + +class GetSecuritySettingsRequest(proto.Message): + r"""The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.GetSecuritySettings]. + + Attributes: + name (str): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateSecuritySettingsRequest(proto.Message): + r"""The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings]. + + Attributes: + security_settings (~.gcdc_security_settings.SecuritySettings): + Required. [SecuritySettings] object that contains values for + each of the fields to update. + update_mask (~.field_mask.FieldMask): + Required. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + security_settings = proto.Field( + proto.MESSAGE, number=1, message="SecuritySettings", + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class ListSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.ListSecuritySettings][]. + + Attributes: + parent (str): + Required. The location to list all security settings for. + Format: ``projects//locations/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListSecuritySettingsResponse(proto.Message): + r"""The response message for [SecuritySettings.ListSecuritySettings][]. + + Attributes: + security_settings (Sequence[~.gcdc_security_settings.SecuritySettings]): + The list of security settings. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + security_settings = proto.RepeatedField( + proto.MESSAGE, number=1, message="SecuritySettings", + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class CreateSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.CreateSecuritySettings][]. + + Attributes: + parent (str): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + for. Format: + ``projects//locations/``. + security_settings (~.gcdc_security_settings.SecuritySettings): + Required. The security settings to create. + """ + + parent = proto.Field(proto.STRING, number=1) + + security_settings = proto.Field( + proto.MESSAGE, number=2, message="SecuritySettings", + ) + + +class DeleteSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.DeleteSecuritySettings][]. + + Attributes: + name (str): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class SecuritySettings(proto.Message): + r"""Represents the settings related to security issues, such as + data redaction and data retention. It may take hours for updates + on the settings to propagate to all the related components and + take effect. + + Attributes: + name (str): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + display_name (str): + Required. The human-readable name of the + security settings, unique within the location. + redaction_strategy (~.gcdc_security_settings.SecuritySettings.RedactionStrategy): + Strategy that defines how we do redaction. + redaction_scope (~.gcdc_security_settings.SecuritySettings.RedactionScope): + Defines on what data we apply redaction. Note + that we don't redact data to which we don't have + access, e.g., Stackdriver logs. + inspect_template (str): + DLP inspect template name. Use this template to define + inspect base settings. + + If empty, we use the default DLP inspect config. + + The template name will have one of the following formats: + ``projects/PROJECT_ID/inspectTemplates/TEMPLATE_ID`` OR + ``organizations/ORGANIZATION_ID/inspectTemplates/TEMPLATE_ID`` + retention_window_days (int): + Retains the data for the specified number of + days. User must Set a value lower than + Dialogflow's default 30d TTL. Setting a value + higher than that has no effect. + A missing value or setting to 0 also means we + use Dialogflow's default TTL. + purge_data_types (Sequence[~.gcdc_security_settings.SecuritySettings.PurgeDataType]): + List of types of data to remove when + retention settings triggers purge. + """ + + class RedactionStrategy(proto.Enum): + r"""Defines how we redact data.""" + REDACTION_STRATEGY_UNSPECIFIED = 0 + REDACT_WITH_SERVICE = 1 + + class RedactionScope(proto.Enum): + r"""Defines what types of data to redact.""" + REDACTION_SCOPE_UNSPECIFIED = 0 + REDACT_DISK_STORAGE = 2 + + class PurgeDataType(proto.Enum): + r"""Type of data we purge after retention settings triggers + purge. + """ + PURGE_DATA_TYPE_UNSPECIFIED = 0 + DIALOGFLOW_HISTORY = 1 + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + redaction_strategy = proto.Field(proto.ENUM, number=3, enum=RedactionStrategy,) + + redaction_scope = proto.Field(proto.ENUM, number=4, enum=RedactionScope,) + + inspect_template = proto.Field(proto.STRING, number=9) + + retention_window_days = proto.Field(proto.INT32, number=6, oneof="data_retention") + + purge_data_types = proto.RepeatedField(proto.ENUM, number=8, enum=PurgeDataType,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/session.py b/google/cloud/dialogflowcx_v3beta1/types/session.py index 593e1aff..dbb8de0c 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/session.py +++ b/google/cloud/dialogflowcx_v3beta1/types/session.py @@ -381,8 +381,8 @@ class QueryParameters(proto.Message): - MapValue type: - If parameter's entity type is a composite entity: map - - Else: string or number, depending on parameter value - type + - Else: depending on parameter value type, could be one + of string, number, boolean, null, list or map - MapValue value: @@ -510,8 +510,8 @@ class QueryResult(proto.Message): - MapValue type: - If parameter's entity type is a composite entity: map - - Else: string or number, depending on parameter value - type + - Else: depending on parameter value type, could be one + of string, number, boolean, null, list or map - MapValue value: @@ -715,9 +715,10 @@ class Match(proto.Message): - MapKey value: parameter name - MapValue type: - If parameter's entity type is a - composite entity: map - Else: string or - number, depending on parameter value type - - MapValue value: + composite entity: map - Else: depending on + parameter value type, could be one of string, + number, boolean, null, list or map + - MapValue value: - If parameter's entity type is a composite entity: map from composite entity property names to property values - diff --git a/synth.metadata b/synth.metadata index 8d61013d..4049b5a4 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "5256ab60f3d396a3d1bd393043776936b9651c5b", - "internalRef": "347703845" + "sha": "69697504d9eba1d064820c3085b4750767be6d08", + "internalRef": "348952930" } }, { @@ -137,6 +137,14 @@ "google/cloud/dialogflowcx_v3/services/environments/transports/base.py", "google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py", "google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py", + "google/cloud/dialogflowcx_v3/services/experiments/__init__.py", + "google/cloud/dialogflowcx_v3/services/experiments/async_client.py", + "google/cloud/dialogflowcx_v3/services/experiments/client.py", + "google/cloud/dialogflowcx_v3/services/experiments/pagers.py", + "google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py", + "google/cloud/dialogflowcx_v3/services/experiments/transports/base.py", + "google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py", + "google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py", "google/cloud/dialogflowcx_v3/services/flows/__init__.py", "google/cloud/dialogflowcx_v3/services/flows/async_client.py", "google/cloud/dialogflowcx_v3/services/flows/client.py", @@ -213,6 +221,7 @@ "google/cloud/dialogflowcx_v3/types/audio_config.py", "google/cloud/dialogflowcx_v3/types/entity_type.py", "google/cloud/dialogflowcx_v3/types/environment.py", + "google/cloud/dialogflowcx_v3/types/experiment.py", "google/cloud/dialogflowcx_v3/types/flow.py", "google/cloud/dialogflowcx_v3/types/fulfillment.py", "google/cloud/dialogflowcx_v3/types/intent.py", @@ -251,6 +260,14 @@ "google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py", "google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py", "google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py", + "google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py", + "google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py", + "google/cloud/dialogflowcx_v3beta1/services/experiments/client.py", + "google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py", + "google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py", + "google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py", + "google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py", + "google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py", "google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py", "google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py", "google/cloud/dialogflowcx_v3beta1/services/flows/client.py", @@ -275,6 +292,14 @@ "google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py", "google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py", "google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py", + "google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py", + "google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py", + "google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py", + "google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py", + "google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py", + "google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py", + "google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py", + "google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py", "google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py", "google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py", "google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py", @@ -319,11 +344,13 @@ "google/cloud/dialogflowcx_v3beta1/types/audio_config.py", "google/cloud/dialogflowcx_v3beta1/types/entity_type.py", "google/cloud/dialogflowcx_v3beta1/types/environment.py", + "google/cloud/dialogflowcx_v3beta1/types/experiment.py", "google/cloud/dialogflowcx_v3beta1/types/flow.py", "google/cloud/dialogflowcx_v3beta1/types/fulfillment.py", "google/cloud/dialogflowcx_v3beta1/types/intent.py", "google/cloud/dialogflowcx_v3beta1/types/page.py", "google/cloud/dialogflowcx_v3beta1/types/response_message.py", + "google/cloud/dialogflowcx_v3beta1/types/security_settings.py", "google/cloud/dialogflowcx_v3beta1/types/session.py", "google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py", "google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py", @@ -345,6 +372,7 @@ "tests/unit/gapic/dialogflowcx_v3/test_agents.py", "tests/unit/gapic/dialogflowcx_v3/test_entity_types.py", "tests/unit/gapic/dialogflowcx_v3/test_environments.py", + "tests/unit/gapic/dialogflowcx_v3/test_experiments.py", "tests/unit/gapic/dialogflowcx_v3/test_flows.py", "tests/unit/gapic/dialogflowcx_v3/test_intents.py", "tests/unit/gapic/dialogflowcx_v3/test_pages.py", @@ -358,9 +386,11 @@ "tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py", "tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py", "tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py", + "tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py", "tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py", "tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py", "tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py", + "tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py", "tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py", "tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py", "tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py", diff --git a/tests/unit/gapic/dialogflowcx_v3/test_experiments.py b/tests/unit/gapic/dialogflowcx_v3/test_experiments.py new file mode 100644 index 00000000..1818b5af --- /dev/null +++ b/tests/unit/gapic/dialogflowcx_v3/test_experiments.py @@ -0,0 +1,2571 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import 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.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflowcx_v3.services.experiments import ExperimentsAsyncClient +from google.cloud.dialogflowcx_v3.services.experiments import ExperimentsClient +from google.cloud.dialogflowcx_v3.services.experiments import pagers +from google.cloud.dialogflowcx_v3.services.experiments import transports +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.oauth2 import service_account +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +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 ExperimentsClient._get_default_mtls_endpoint(None) is None + assert ( + ExperimentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + ExperimentsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ExperimentsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ExperimentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ExperimentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ExperimentsClient, ExperimentsAsyncClient]) +def test_experiments_client_from_service_account_file(client_class): + creds = 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") + assert client.transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_experiments_client_get_transport_class(): + transport = ExperimentsClient.get_transport_class() + assert transport == transports.ExperimentsGrpcTransport + + transport = ExperimentsClient.get_transport_class("grpc") + assert transport == transports.ExperimentsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + ( + ExperimentsAsyncClient, + transports.ExperimentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient) +) +@mock.patch.object( + ExperimentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ExperimentsAsyncClient), +) +def test_experiments_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(ExperimentsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=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(ExperimentsClient, "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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + + # 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() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "true"), + ( + ExperimentsAsyncClient, + transports.ExperimentsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "false"), + ( + ExperimentsAsyncClient, + transports.ExperimentsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient) +) +@mock.patch.object( + ExperimentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ExperimentsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_experiments_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: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + ( + ExperimentsAsyncClient, + transports.ExperimentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_experiments_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + ( + ExperimentsAsyncClient, + transports.ExperimentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_experiments_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_experiments_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ExperimentsClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_experiments( + transport: str = "grpc", request_type=experiment.ListExperimentsRequest +): + client = ExperimentsClient( + credentials=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_experiments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.ListExperimentsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListExperimentsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_experiments_from_dict(): + test_list_experiments(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_experiments_async( + transport: str = "grpc_asyncio", request_type=experiment.ListExperimentsRequest +): + client = ExperimentsAsyncClient( + credentials=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_experiments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.ListExperimentsResponse(next_page_token="next_page_token_value",) + ) + + response = await client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.ListExperimentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExperimentsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_experiments_async_from_dict(): + await test_list_experiments_async(request_type=dict) + + +def test_list_experiments_field_headers(): + client = ExperimentsClient(credentials=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 = experiment.ListExperimentsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + call.return_value = experiment.ListExperimentsResponse() + + client.list_experiments(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_experiments_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = experiment.ListExperimentsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.ListExperimentsResponse() + ) + + await client.list_experiments(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_experiments_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_experiments(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] + + assert args[0].parent == "parent_value" + + +def test_list_experiments_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_experiments( + experiment.ListExperimentsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_experiments_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.ListExperimentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_experiments(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] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_experiments_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=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_experiments( + experiment.ListExperimentsRequest(), parent="parent_value", + ) + + +def test_list_experiments_pager(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token="abc", + ), + experiment.ListExperimentsResponse(experiments=[], next_page_token="def",), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(),], next_page_token="ghi", + ), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(), experiment.Experiment(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_experiments(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, experiment.Experiment) for i in results) + + +def test_list_experiments_pages(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token="abc", + ), + experiment.ListExperimentsResponse(experiments=[], next_page_token="def",), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(),], next_page_token="ghi", + ), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(), experiment.Experiment(),], + ), + RuntimeError, + ) + pages = list(client.list_experiments(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_experiments_async_pager(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token="abc", + ), + experiment.ListExperimentsResponse(experiments=[], next_page_token="def",), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(),], next_page_token="ghi", + ), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(), experiment.Experiment(),], + ), + RuntimeError, + ) + async_pager = await client.list_experiments(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, experiment.Experiment) for i in responses) + + +@pytest.mark.asyncio +async def test_list_experiments_async_pages(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token="abc", + ), + experiment.ListExperimentsResponse(experiments=[], next_page_token="def",), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(),], next_page_token="ghi", + ), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(), experiment.Experiment(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_experiments(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_experiment( + transport: str = "grpc", request_type=experiment.GetExperimentRequest +): + client = ExperimentsClient( + credentials=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_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + + response = client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.GetExperimentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +def test_get_experiment_from_dict(): + test_get_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_experiment_async( + transport: str = "grpc_asyncio", request_type=experiment.GetExperimentRequest +): + client = ExperimentsAsyncClient( + credentials=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_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + ) + + response = await client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.GetExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_get_experiment_async_from_dict(): + await test_get_experiment_async(request_type=dict) + + +def test_get_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = experiment.GetExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: + call.return_value = experiment.Experiment() + + client.get_experiment(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_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = experiment.GetExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + + await client.get_experiment(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_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_experiment(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] + + assert args[0].name == "name_value" + + +def test_get_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_experiment( + experiment.GetExperimentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_experiment(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] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=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_experiment( + experiment.GetExperimentRequest(), name="name_value", + ) + + +def test_create_experiment( + transport: str = "grpc", request_type=gcdc_experiment.CreateExperimentRequest +): + client = ExperimentsClient( + credentials=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_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=gcdc_experiment.Experiment.State.DRAFT, + ) + + response = client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_experiment.CreateExperimentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcdc_experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +def test_create_experiment_from_dict(): + test_create_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_experiment_async( + transport: str = "grpc_asyncio", + request_type=gcdc_experiment.CreateExperimentRequest, +): + client = ExperimentsAsyncClient( + credentials=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_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=gcdc_experiment.Experiment.State.DRAFT, + ) + ) + + response = await client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_experiment.CreateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_create_experiment_async_from_dict(): + await test_create_experiment_async(request_type=dict) + + +def test_create_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = gcdc_experiment.CreateExperimentRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), "__call__" + ) as call: + call.return_value = gcdc_experiment.Experiment() + + client.create_experiment(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_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = gcdc_experiment.CreateExperimentRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment() + ) + + await client.create_experiment(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_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_experiment( + parent="parent_value", + experiment=gcdc_experiment.Experiment(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] + + assert args[0].parent == "parent_value" + + assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") + + +def test_create_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_experiment( + gcdc_experiment.CreateExperimentRequest(), + parent="parent_value", + experiment=gcdc_experiment.Experiment(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_experiment( + parent="parent_value", + experiment=gcdc_experiment.Experiment(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] + + assert args[0].parent == "parent_value" + + assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") + + +@pytest.mark.asyncio +async def test_create_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=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_experiment( + gcdc_experiment.CreateExperimentRequest(), + parent="parent_value", + experiment=gcdc_experiment.Experiment(name="name_value"), + ) + + +def test_update_experiment( + transport: str = "grpc", request_type=gcdc_experiment.UpdateExperimentRequest +): + client = ExperimentsClient( + credentials=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_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=gcdc_experiment.Experiment.State.DRAFT, + ) + + response = client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_experiment.UpdateExperimentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcdc_experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +def test_update_experiment_from_dict(): + test_update_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_experiment_async( + transport: str = "grpc_asyncio", + request_type=gcdc_experiment.UpdateExperimentRequest, +): + client = ExperimentsAsyncClient( + credentials=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_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=gcdc_experiment.Experiment.State.DRAFT, + ) + ) + + response = await client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_experiment.UpdateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_update_experiment_async_from_dict(): + await test_update_experiment_async(request_type=dict) + + +def test_update_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = gcdc_experiment.UpdateExperimentRequest() + request.experiment.name = "experiment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), "__call__" + ) as call: + call.return_value = gcdc_experiment.Experiment() + + client.update_experiment(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", "experiment.name=experiment.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = gcdc_experiment.UpdateExperimentRequest() + request.experiment.name = "experiment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment() + ) + + await client.update_experiment(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", "experiment.name=experiment.name/value",) in kw[ + "metadata" + ] + + +def test_update_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_experiment( + experiment=gcdc_experiment.Experiment(name="name_value"), + update_mask=field_mask.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] + + assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_experiment( + gcdc_experiment.UpdateExperimentRequest(), + experiment=gcdc_experiment.Experiment(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_experiment( + experiment=gcdc_experiment.Experiment(name="name_value"), + update_mask=field_mask.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] + + assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=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_experiment( + gcdc_experiment.UpdateExperimentRequest(), + experiment=gcdc_experiment.Experiment(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_experiment( + transport: str = "grpc", request_type=experiment.DeleteExperimentRequest +): + client = ExperimentsClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.DeleteExperimentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_experiment_from_dict(): + test_delete_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_experiment_async( + transport: str = "grpc_asyncio", request_type=experiment.DeleteExperimentRequest +): + client = ExperimentsAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.DeleteExperimentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_experiment_async_from_dict(): + await test_delete_experiment_async(request_type=dict) + + +def test_delete_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = experiment.DeleteExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + call.return_value = None + + client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = experiment.DeleteExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_experiment(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_delete_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_experiment(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] + + assert args[0].name == "name_value" + + +def test_delete_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_experiment( + experiment.DeleteExperimentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_experiment(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] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_experiment( + experiment.DeleteExperimentRequest(), name="name_value", + ) + + +def test_start_experiment( + transport: str = "grpc", request_type=experiment.StartExperimentRequest +): + client = ExperimentsClient( + credentials=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.start_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + + response = client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.StartExperimentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +def test_start_experiment_from_dict(): + test_start_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_start_experiment_async( + transport: str = "grpc_asyncio", request_type=experiment.StartExperimentRequest +): + client = ExperimentsAsyncClient( + credentials=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.start_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + ) + + response = await client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.StartExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_start_experiment_async_from_dict(): + await test_start_experiment_async(request_type=dict) + + +def test_start_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = experiment.StartExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: + call.return_value = experiment.Experiment() + + client.start_experiment(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_start_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = experiment.StartExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + + await client.start_experiment(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_start_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_experiment(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] + + assert args[0].name == "name_value" + + +def test_start_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_experiment( + experiment.StartExperimentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_start_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_experiment(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] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_start_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_experiment( + experiment.StartExperimentRequest(), name="name_value", + ) + + +def test_stop_experiment( + transport: str = "grpc", request_type=experiment.StopExperimentRequest +): + client = ExperimentsClient( + credentials=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.stop_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + + response = client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.StopExperimentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +def test_stop_experiment_from_dict(): + test_stop_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_stop_experiment_async( + transport: str = "grpc_asyncio", request_type=experiment.StopExperimentRequest +): + client = ExperimentsAsyncClient( + credentials=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.stop_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + ) + + response = await client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.StopExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_stop_experiment_async_from_dict(): + await test_stop_experiment_async(request_type=dict) + + +def test_stop_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = experiment.StopExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: + call.return_value = experiment.Experiment() + + client.stop_experiment(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_stop_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = experiment.StopExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + + await client.stop_experiment(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_stop_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.stop_experiment(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] + + assert args[0].name == "name_value" + + +def test_stop_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_experiment( + experiment.StopExperimentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_stop_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.stop_experiment(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] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_stop_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_experiment( + experiment.StopExperimentRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = ExperimentsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ExperimentsGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.ExperimentsGrpcTransport,) + + +def test_experiments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.ExperimentsTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_experiments_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ExperimentsTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_experiments", + "get_experiment", + "create_experiment", + "update_experiment", + "delete_experiment", + "start_experiment", + "stop_experiment", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_experiments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ExperimentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_experiments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ExperimentsTransport() + adc.assert_called_once() + + +def test_experiments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + ExperimentsClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +def test_experiments_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.ExperimentsGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_experiments_host_no_port(): + client = ExperimentsClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_experiments_host_with_port(): + client = ExperimentsClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:8000" + + +def test_experiments_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ExperimentsGrpcTransport( + 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_experiments_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ExperimentsGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +@pytest.mark.parametrize( + "transport_class", + [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport], +) +def test_experiments_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", autospec=True + ) 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 = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + 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 + + +@pytest.mark.parametrize( + "transport_class", + [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport], +) +def test_experiments_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", autospec=True + ) 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + 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_experiment_path(): + project = "squid" + location = "clam" + agent = "whelk" + environment = "octopus" + experiment = "oyster" + + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format( + project=project, + location=location, + agent=agent, + environment=environment, + experiment=experiment, + ) + actual = ExperimentsClient.experiment_path( + project, location, agent, environment, experiment + ) + assert expected == actual + + +def test_parse_experiment_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "environment": "winkle", + "experiment": "nautilus", + } + path = ExperimentsClient.experiment_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_experiment_path(path) + assert expected == actual + + +def test_version_path(): + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" + version = "whelk" + + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( + project=project, location=location, agent=agent, flow=flow, version=version, + ) + actual = ExperimentsClient.version_path(project, location, agent, flow, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "version": "mussel", + } + path = ExperimentsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_version_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ExperimentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ExperimentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + + expected = "folders/{folder}".format(folder=folder,) + actual = ExperimentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ExperimentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + + expected = "organizations/{organization}".format(organization=organization,) + actual = ExperimentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ExperimentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + + expected = "projects/{project}".format(project=project,) + actual = ExperimentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ExperimentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.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 = ExperimentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ExperimentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ExperimentsTransport, "_prep_wrapped_messages" + ) as prep: + client = ExperimentsClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ExperimentsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ExperimentsClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py new file mode 100644 index 00000000..2f9feb9e --- /dev/null +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py @@ -0,0 +1,2573 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import 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.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflowcx_v3beta1.services.experiments import ( + ExperimentsAsyncClient, +) +from google.cloud.dialogflowcx_v3beta1.services.experiments import ExperimentsClient +from google.cloud.dialogflowcx_v3beta1.services.experiments import pagers +from google.cloud.dialogflowcx_v3beta1.services.experiments import transports +from google.cloud.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.oauth2 import service_account +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +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 ExperimentsClient._get_default_mtls_endpoint(None) is None + assert ( + ExperimentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + ExperimentsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ExperimentsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ExperimentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ExperimentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ExperimentsClient, ExperimentsAsyncClient]) +def test_experiments_client_from_service_account_file(client_class): + creds = 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") + assert client.transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_experiments_client_get_transport_class(): + transport = ExperimentsClient.get_transport_class() + assert transport == transports.ExperimentsGrpcTransport + + transport = ExperimentsClient.get_transport_class("grpc") + assert transport == transports.ExperimentsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + ( + ExperimentsAsyncClient, + transports.ExperimentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient) +) +@mock.patch.object( + ExperimentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ExperimentsAsyncClient), +) +def test_experiments_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(ExperimentsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=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(ExperimentsClient, "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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + + # 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() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "true"), + ( + ExperimentsAsyncClient, + transports.ExperimentsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "false"), + ( + ExperimentsAsyncClient, + transports.ExperimentsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient) +) +@mock.patch.object( + ExperimentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ExperimentsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_experiments_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: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + ( + ExperimentsAsyncClient, + transports.ExperimentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_experiments_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + ( + ExperimentsAsyncClient, + transports.ExperimentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_experiments_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_experiments_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ExperimentsClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_experiments( + transport: str = "grpc", request_type=experiment.ListExperimentsRequest +): + client = ExperimentsClient( + credentials=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_experiments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.ListExperimentsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListExperimentsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_experiments_from_dict(): + test_list_experiments(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_experiments_async( + transport: str = "grpc_asyncio", request_type=experiment.ListExperimentsRequest +): + client = ExperimentsAsyncClient( + credentials=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_experiments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.ListExperimentsResponse(next_page_token="next_page_token_value",) + ) + + response = await client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.ListExperimentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExperimentsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_experiments_async_from_dict(): + await test_list_experiments_async(request_type=dict) + + +def test_list_experiments_field_headers(): + client = ExperimentsClient(credentials=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 = experiment.ListExperimentsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + call.return_value = experiment.ListExperimentsResponse() + + client.list_experiments(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_experiments_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = experiment.ListExperimentsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.ListExperimentsResponse() + ) + + await client.list_experiments(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_experiments_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_experiments(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] + + assert args[0].parent == "parent_value" + + +def test_list_experiments_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_experiments( + experiment.ListExperimentsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_experiments_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.ListExperimentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_experiments(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] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_experiments_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=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_experiments( + experiment.ListExperimentsRequest(), parent="parent_value", + ) + + +def test_list_experiments_pager(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token="abc", + ), + experiment.ListExperimentsResponse(experiments=[], next_page_token="def",), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(),], next_page_token="ghi", + ), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(), experiment.Experiment(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_experiments(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, experiment.Experiment) for i in results) + + +def test_list_experiments_pages(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token="abc", + ), + experiment.ListExperimentsResponse(experiments=[], next_page_token="def",), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(),], next_page_token="ghi", + ), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(), experiment.Experiment(),], + ), + RuntimeError, + ) + pages = list(client.list_experiments(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_experiments_async_pager(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token="abc", + ), + experiment.ListExperimentsResponse(experiments=[], next_page_token="def",), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(),], next_page_token="ghi", + ), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(), experiment.Experiment(),], + ), + RuntimeError, + ) + async_pager = await client.list_experiments(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, experiment.Experiment) for i in responses) + + +@pytest.mark.asyncio +async def test_list_experiments_async_pages(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token="abc", + ), + experiment.ListExperimentsResponse(experiments=[], next_page_token="def",), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(),], next_page_token="ghi", + ), + experiment.ListExperimentsResponse( + experiments=[experiment.Experiment(), experiment.Experiment(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_experiments(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_experiment( + transport: str = "grpc", request_type=experiment.GetExperimentRequest +): + client = ExperimentsClient( + credentials=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_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + + response = client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.GetExperimentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +def test_get_experiment_from_dict(): + test_get_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_experiment_async( + transport: str = "grpc_asyncio", request_type=experiment.GetExperimentRequest +): + client = ExperimentsAsyncClient( + credentials=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_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + ) + + response = await client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.GetExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_get_experiment_async_from_dict(): + await test_get_experiment_async(request_type=dict) + + +def test_get_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = experiment.GetExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: + call.return_value = experiment.Experiment() + + client.get_experiment(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_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = experiment.GetExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + + await client.get_experiment(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_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_experiment(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] + + assert args[0].name == "name_value" + + +def test_get_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_experiment( + experiment.GetExperimentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_experiment(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] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=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_experiment( + experiment.GetExperimentRequest(), name="name_value", + ) + + +def test_create_experiment( + transport: str = "grpc", request_type=gcdc_experiment.CreateExperimentRequest +): + client = ExperimentsClient( + credentials=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_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=gcdc_experiment.Experiment.State.DRAFT, + ) + + response = client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_experiment.CreateExperimentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcdc_experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +def test_create_experiment_from_dict(): + test_create_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_experiment_async( + transport: str = "grpc_asyncio", + request_type=gcdc_experiment.CreateExperimentRequest, +): + client = ExperimentsAsyncClient( + credentials=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_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=gcdc_experiment.Experiment.State.DRAFT, + ) + ) + + response = await client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_experiment.CreateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_create_experiment_async_from_dict(): + await test_create_experiment_async(request_type=dict) + + +def test_create_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = gcdc_experiment.CreateExperimentRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), "__call__" + ) as call: + call.return_value = gcdc_experiment.Experiment() + + client.create_experiment(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_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = gcdc_experiment.CreateExperimentRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment() + ) + + await client.create_experiment(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_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_experiment( + parent="parent_value", + experiment=gcdc_experiment.Experiment(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] + + assert args[0].parent == "parent_value" + + assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") + + +def test_create_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_experiment( + gcdc_experiment.CreateExperimentRequest(), + parent="parent_value", + experiment=gcdc_experiment.Experiment(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_experiment( + parent="parent_value", + experiment=gcdc_experiment.Experiment(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] + + assert args[0].parent == "parent_value" + + assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") + + +@pytest.mark.asyncio +async def test_create_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=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_experiment( + gcdc_experiment.CreateExperimentRequest(), + parent="parent_value", + experiment=gcdc_experiment.Experiment(name="name_value"), + ) + + +def test_update_experiment( + transport: str = "grpc", request_type=gcdc_experiment.UpdateExperimentRequest +): + client = ExperimentsClient( + credentials=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_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=gcdc_experiment.Experiment.State.DRAFT, + ) + + response = client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_experiment.UpdateExperimentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcdc_experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +def test_update_experiment_from_dict(): + test_update_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_experiment_async( + transport: str = "grpc_asyncio", + request_type=gcdc_experiment.UpdateExperimentRequest, +): + client = ExperimentsAsyncClient( + credentials=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_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=gcdc_experiment.Experiment.State.DRAFT, + ) + ) + + response = await client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_experiment.UpdateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_update_experiment_async_from_dict(): + await test_update_experiment_async(request_type=dict) + + +def test_update_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = gcdc_experiment.UpdateExperimentRequest() + request.experiment.name = "experiment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), "__call__" + ) as call: + call.return_value = gcdc_experiment.Experiment() + + client.update_experiment(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", "experiment.name=experiment.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = gcdc_experiment.UpdateExperimentRequest() + request.experiment.name = "experiment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment() + ) + + await client.update_experiment(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", "experiment.name=experiment.name/value",) in kw[ + "metadata" + ] + + +def test_update_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_experiment( + experiment=gcdc_experiment.Experiment(name="name_value"), + update_mask=field_mask.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] + + assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_experiment( + gcdc_experiment.UpdateExperimentRequest(), + experiment=gcdc_experiment.Experiment(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_experiment.Experiment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_experiment( + experiment=gcdc_experiment.Experiment(name="name_value"), + update_mask=field_mask.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] + + assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=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_experiment( + gcdc_experiment.UpdateExperimentRequest(), + experiment=gcdc_experiment.Experiment(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_experiment( + transport: str = "grpc", request_type=experiment.DeleteExperimentRequest +): + client = ExperimentsClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.DeleteExperimentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_experiment_from_dict(): + test_delete_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_experiment_async( + transport: str = "grpc_asyncio", request_type=experiment.DeleteExperimentRequest +): + client = ExperimentsAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.DeleteExperimentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_experiment_async_from_dict(): + await test_delete_experiment_async(request_type=dict) + + +def test_delete_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = experiment.DeleteExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + call.return_value = None + + client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = experiment.DeleteExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_experiment(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_delete_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_experiment(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] + + assert args[0].name == "name_value" + + +def test_delete_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_experiment( + experiment.DeleteExperimentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_experiment(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] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_experiment( + experiment.DeleteExperimentRequest(), name="name_value", + ) + + +def test_start_experiment( + transport: str = "grpc", request_type=experiment.StartExperimentRequest +): + client = ExperimentsClient( + credentials=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.start_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + + response = client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.StartExperimentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +def test_start_experiment_from_dict(): + test_start_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_start_experiment_async( + transport: str = "grpc_asyncio", request_type=experiment.StartExperimentRequest +): + client = ExperimentsAsyncClient( + credentials=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.start_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + ) + + response = await client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.StartExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_start_experiment_async_from_dict(): + await test_start_experiment_async(request_type=dict) + + +def test_start_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = experiment.StartExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: + call.return_value = experiment.Experiment() + + client.start_experiment(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_start_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = experiment.StartExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + + await client.start_experiment(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_start_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_experiment(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] + + assert args[0].name == "name_value" + + +def test_start_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_experiment( + experiment.StartExperimentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_start_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_experiment(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] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_start_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_experiment( + experiment.StartExperimentRequest(), name="name_value", + ) + + +def test_stop_experiment( + transport: str = "grpc", request_type=experiment.StopExperimentRequest +): + client = ExperimentsClient( + credentials=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.stop_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + + response = client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.StopExperimentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +def test_stop_experiment_from_dict(): + test_stop_experiment(request_type=dict) + + +@pytest.mark.asyncio +async def test_stop_experiment_async( + transport: str = "grpc_asyncio", request_type=experiment.StopExperimentRequest +): + client = ExperimentsAsyncClient( + credentials=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.stop_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment( + name="name_value", + display_name="display_name_value", + description="description_value", + state=experiment.Experiment.State.DRAFT, + ) + ) + + response = await client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == experiment.StopExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_stop_experiment_async_from_dict(): + await test_stop_experiment_async(request_type=dict) + + +def test_stop_experiment_field_headers(): + client = ExperimentsClient(credentials=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 = experiment.StopExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: + call.return_value = experiment.Experiment() + + client.stop_experiment(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_stop_experiment_field_headers_async(): + client = ExperimentsAsyncClient(credentials=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 = experiment.StopExperimentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + + await client.stop_experiment(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_stop_experiment_flattened(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.stop_experiment(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] + + assert args[0].name == "name_value" + + +def test_stop_experiment_flattened_error(): + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_experiment( + experiment.StopExperimentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_stop_experiment_flattened_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + experiment.Experiment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.stop_experiment(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] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_stop_experiment_flattened_error_async(): + client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_experiment( + experiment.StopExperimentRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = ExperimentsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ExperimentsGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.ExperimentsGrpcTransport,) + + +def test_experiments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.ExperimentsTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_experiments_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ExperimentsTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_experiments", + "get_experiment", + "create_experiment", + "update_experiment", + "delete_experiment", + "start_experiment", + "stop_experiment", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_experiments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ExperimentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_experiments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ExperimentsTransport() + adc.assert_called_once() + + +def test_experiments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + ExperimentsClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +def test_experiments_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.ExperimentsGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_experiments_host_no_port(): + client = ExperimentsClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_experiments_host_with_port(): + client = ExperimentsClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:8000" + + +def test_experiments_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ExperimentsGrpcTransport( + 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_experiments_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ExperimentsGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +@pytest.mark.parametrize( + "transport_class", + [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport], +) +def test_experiments_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", autospec=True + ) 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 = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + 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 + + +@pytest.mark.parametrize( + "transport_class", + [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport], +) +def test_experiments_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", autospec=True + ) 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + 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_experiment_path(): + project = "squid" + location = "clam" + agent = "whelk" + environment = "octopus" + experiment = "oyster" + + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format( + project=project, + location=location, + agent=agent, + environment=environment, + experiment=experiment, + ) + actual = ExperimentsClient.experiment_path( + project, location, agent, environment, experiment + ) + assert expected == actual + + +def test_parse_experiment_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "environment": "winkle", + "experiment": "nautilus", + } + path = ExperimentsClient.experiment_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_experiment_path(path) + assert expected == actual + + +def test_version_path(): + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" + version = "whelk" + + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( + project=project, location=location, agent=agent, flow=flow, version=version, + ) + actual = ExperimentsClient.version_path(project, location, agent, flow, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "version": "mussel", + } + path = ExperimentsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_version_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ExperimentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ExperimentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + + expected = "folders/{folder}".format(folder=folder,) + actual = ExperimentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ExperimentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + + expected = "organizations/{organization}".format(organization=organization,) + actual = ExperimentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ExperimentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + + expected = "projects/{project}".format(project=project,) + actual = ExperimentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ExperimentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.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 = ExperimentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ExperimentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ExperimentsTransport, "_prep_wrapped_messages" + ) as prep: + client = ExperimentsClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ExperimentsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ExperimentsClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py new file mode 100644 index 00000000..42abad67 --- /dev/null +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py @@ -0,0 +1,2418 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import 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.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import ( + SecuritySettingsServiceAsyncClient, +) +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import ( + SecuritySettingsServiceClient, +) +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import ( + transports, +) +from google.cloud.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import ( + security_settings as gcdc_security_settings, +) +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +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 SecuritySettingsServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SecuritySettingsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SecuritySettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SecuritySettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SecuritySettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SecuritySettingsServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [SecuritySettingsServiceClient, SecuritySettingsServiceAsyncClient] +) +def test_security_settings_service_client_from_service_account_file(client_class): + creds = 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") + assert client.transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_security_settings_service_client_get_transport_class(): + transport = SecuritySettingsServiceClient.get_transport_class() + assert transport == transports.SecuritySettingsServiceGrpcTransport + + transport = SecuritySettingsServiceClient.get_transport_class("grpc") + assert transport == transports.SecuritySettingsServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SecuritySettingsServiceClient, + transports.SecuritySettingsServiceGrpcTransport, + "grpc", + ), + ( + SecuritySettingsServiceAsyncClient, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + SecuritySettingsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecuritySettingsServiceClient), +) +@mock.patch.object( + SecuritySettingsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecuritySettingsServiceAsyncClient), +) +def test_security_settings_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(SecuritySettingsServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=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(SecuritySettingsServiceClient, "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(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + + # 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() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + SecuritySettingsServiceClient, + transports.SecuritySettingsServiceGrpcTransport, + "grpc", + "true", + ), + ( + SecuritySettingsServiceAsyncClient, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SecuritySettingsServiceClient, + transports.SecuritySettingsServiceGrpcTransport, + "grpc", + "false", + ), + ( + SecuritySettingsServiceAsyncClient, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + SecuritySettingsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecuritySettingsServiceClient), +) +@mock.patch.object( + SecuritySettingsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecuritySettingsServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_settings_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: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SecuritySettingsServiceClient, + transports.SecuritySettingsServiceGrpcTransport, + "grpc", + ), + ( + SecuritySettingsServiceAsyncClient, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_security_settings_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SecuritySettingsServiceClient, + transports.SecuritySettingsServiceGrpcTransport, + "grpc", + ), + ( + SecuritySettingsServiceAsyncClient, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_security_settings_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_security_settings_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SecuritySettingsServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_security_settings( + transport: str = "grpc", + request_type=gcdc_security_settings.CreateSecuritySettingsRequest, +): + client = SecuritySettingsServiceClient( + credentials=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_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings( + name="name_value", + display_name="display_name_value", + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template="inspect_template_value", + purge_data_types=[ + gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ], + retention_window_days=2271, + ) + + response = client.create_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcdc_security_settings.SecuritySettings) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert ( + response.redaction_strategy + == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + ) + + assert ( + response.redaction_scope + == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + ) + + assert response.inspect_template == "inspect_template_value" + + assert response.purge_data_types == [ + gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ] + + +def test_create_security_settings_from_dict(): + test_create_security_settings(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_security_settings_async( + transport: str = "grpc_asyncio", + request_type=gcdc_security_settings.CreateSecuritySettingsRequest, +): + client = SecuritySettingsServiceAsyncClient( + credentials=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_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_security_settings.SecuritySettings( + name="name_value", + display_name="display_name_value", + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template="inspect_template_value", + purge_data_types=[ + gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ], + ) + ) + + response = await client.create_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_security_settings.SecuritySettings) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert ( + response.redaction_strategy + == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + ) + + assert ( + response.redaction_scope + == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + ) + + assert response.inspect_template == "inspect_template_value" + + assert response.purge_data_types == [ + gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ] + + +@pytest.mark.asyncio +async def test_create_security_settings_async_from_dict(): + await test_create_security_settings_async(request_type=dict) + + +def test_create_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=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 = gcdc_security_settings.CreateSecuritySettingsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), "__call__" + ) as call: + call.return_value = gcdc_security_settings.SecuritySettings() + + client.create_security_settings(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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=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 = gcdc_security_settings.CreateSecuritySettingsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_security_settings.SecuritySettings() + ) + + await client.create_security_settings(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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_security_settings( + parent="parent_value", + security_settings=gcdc_security_settings.SecuritySettings( + 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] + + assert args[0].parent == "parent_value" + + assert args[0].security_settings == gcdc_security_settings.SecuritySettings( + name="name_value" + ) + + +def test_create_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_security_settings( + gcdc_security_settings.CreateSecuritySettingsRequest(), + parent="parent_value", + security_settings=gcdc_security_settings.SecuritySettings( + name="name_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_security_settings.SecuritySettings() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_security_settings( + parent="parent_value", + security_settings=gcdc_security_settings.SecuritySettings( + 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] + + assert args[0].parent == "parent_value" + + assert args[0].security_settings == gcdc_security_settings.SecuritySettings( + name="name_value" + ) + + +@pytest.mark.asyncio +async def test_create_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=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_security_settings( + gcdc_security_settings.CreateSecuritySettingsRequest(), + parent="parent_value", + security_settings=gcdc_security_settings.SecuritySettings( + name="name_value" + ), + ) + + +def test_get_security_settings( + transport: str = "grpc", request_type=security_settings.GetSecuritySettingsRequest +): + client = SecuritySettingsServiceClient( + credentials=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_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.SecuritySettings( + name="name_value", + display_name="display_name_value", + redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template="inspect_template_value", + purge_data_types=[ + security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ], + retention_window_days=2271, + ) + + response = client.get_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == security_settings.GetSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, security_settings.SecuritySettings) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert ( + response.redaction_strategy + == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + ) + + assert ( + response.redaction_scope + == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + ) + + assert response.inspect_template == "inspect_template_value" + + assert response.purge_data_types == [ + security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ] + + +def test_get_security_settings_from_dict(): + test_get_security_settings(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_security_settings_async( + transport: str = "grpc_asyncio", + request_type=security_settings.GetSecuritySettingsRequest, +): + client = SecuritySettingsServiceAsyncClient( + credentials=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_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_settings.SecuritySettings( + name="name_value", + display_name="display_name_value", + redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template="inspect_template_value", + purge_data_types=[ + security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ], + ) + ) + + response = await client.get_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == security_settings.GetSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, security_settings.SecuritySettings) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert ( + response.redaction_strategy + == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + ) + + assert ( + response.redaction_scope + == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + ) + + assert response.inspect_template == "inspect_template_value" + + assert response.purge_data_types == [ + security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ] + + +@pytest.mark.asyncio +async def test_get_security_settings_async_from_dict(): + await test_get_security_settings_async(request_type=dict) + + +def test_get_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=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 = security_settings.GetSecuritySettingsRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), "__call__" + ) as call: + call.return_value = security_settings.SecuritySettings() + + client.get_security_settings(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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=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 = security_settings.GetSecuritySettingsRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_settings.SecuritySettings() + ) + + await client.get_security_settings(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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.SecuritySettings() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_security_settings(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] + + assert args[0].name == "name_value" + + +def test_get_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_security_settings( + security_settings.GetSecuritySettingsRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.SecuritySettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_settings.SecuritySettings() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_security_settings(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] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=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_security_settings( + security_settings.GetSecuritySettingsRequest(), name="name_value", + ) + + +def test_update_security_settings( + transport: str = "grpc", + request_type=gcdc_security_settings.UpdateSecuritySettingsRequest, +): + client = SecuritySettingsServiceClient( + credentials=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_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings( + name="name_value", + display_name="display_name_value", + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template="inspect_template_value", + purge_data_types=[ + gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ], + retention_window_days=2271, + ) + + response = client.update_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcdc_security_settings.SecuritySettings) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert ( + response.redaction_strategy + == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + ) + + assert ( + response.redaction_scope + == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + ) + + assert response.inspect_template == "inspect_template_value" + + assert response.purge_data_types == [ + gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ] + + +def test_update_security_settings_from_dict(): + test_update_security_settings(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_security_settings_async( + transport: str = "grpc_asyncio", + request_type=gcdc_security_settings.UpdateSecuritySettingsRequest, +): + client = SecuritySettingsServiceAsyncClient( + credentials=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_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_security_settings.SecuritySettings( + name="name_value", + display_name="display_name_value", + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template="inspect_template_value", + purge_data_types=[ + gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ], + ) + ) + + response = await client.update_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_security_settings.SecuritySettings) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert ( + response.redaction_strategy + == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + ) + + assert ( + response.redaction_scope + == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + ) + + assert response.inspect_template == "inspect_template_value" + + assert response.purge_data_types == [ + gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY + ] + + +@pytest.mark.asyncio +async def test_update_security_settings_async_from_dict(): + await test_update_security_settings_async(request_type=dict) + + +def test_update_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=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 = gcdc_security_settings.UpdateSecuritySettingsRequest() + request.security_settings.name = "security_settings.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), "__call__" + ) as call: + call.return_value = gcdc_security_settings.SecuritySettings() + + client.update_security_settings(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", + "security_settings.name=security_settings.name/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=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 = gcdc_security_settings.UpdateSecuritySettingsRequest() + request.security_settings.name = "security_settings.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_security_settings.SecuritySettings() + ) + + await client.update_security_settings(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", + "security_settings.name=security_settings.name/value", + ) in kw["metadata"] + + +def test_update_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_settings( + security_settings=gcdc_security_settings.SecuritySettings( + name="name_value" + ), + update_mask=field_mask.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] + + assert args[0].security_settings == gcdc_security_settings.SecuritySettings( + name="name_value" + ) + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_security_settings( + gcdc_security_settings.UpdateSecuritySettingsRequest(), + security_settings=gcdc_security_settings.SecuritySettings( + name="name_value" + ), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_security_settings.SecuritySettings() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_settings( + security_settings=gcdc_security_settings.SecuritySettings( + name="name_value" + ), + update_mask=field_mask.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] + + assert args[0].security_settings == gcdc_security_settings.SecuritySettings( + name="name_value" + ) + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=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_security_settings( + gcdc_security_settings.UpdateSecuritySettingsRequest(), + security_settings=gcdc_security_settings.SecuritySettings( + name="name_value" + ), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_list_security_settings( + transport: str = "grpc", request_type=security_settings.ListSecuritySettingsRequest +): + client = SecuritySettingsServiceClient( + credentials=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_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.ListSecuritySettingsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == security_settings.ListSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListSecuritySettingsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_security_settings_from_dict(): + test_list_security_settings(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_security_settings_async( + transport: str = "grpc_asyncio", + request_type=security_settings.ListSecuritySettingsRequest, +): + client = SecuritySettingsServiceAsyncClient( + credentials=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_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_settings.ListSecuritySettingsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == security_settings.ListSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecuritySettingsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_security_settings_async_from_dict(): + await test_list_security_settings_async(request_type=dict) + + +def test_list_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=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 = security_settings.ListSecuritySettingsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), "__call__" + ) as call: + call.return_value = security_settings.ListSecuritySettingsResponse() + + client.list_security_settings(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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=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 = security_settings.ListSecuritySettingsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_settings.ListSecuritySettingsResponse() + ) + + await client.list_security_settings(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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.ListSecuritySettingsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_security_settings(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] + + assert args[0].parent == "parent_value" + + +def test_list_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_security_settings( + security_settings.ListSecuritySettingsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.ListSecuritySettingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_settings.ListSecuritySettingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_security_settings(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] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=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_security_settings( + security_settings.ListSecuritySettingsRequest(), parent="parent_value", + ) + + +def test_list_security_settings_pager(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token="abc", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], next_page_token="def", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[security_settings.SecuritySettings(),], + next_page_token="ghi", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_security_settings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, security_settings.SecuritySettings) for i in results) + + +def test_list_security_settings_pages(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token="abc", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], next_page_token="def", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[security_settings.SecuritySettings(),], + next_page_token="ghi", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + pages = list(client.list_security_settings(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_security_settings_async_pager(): + client = SecuritySettingsServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token="abc", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], next_page_token="def", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[security_settings.SecuritySettings(),], + next_page_token="ghi", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_security_settings(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, security_settings.SecuritySettings) for i in responses) + + +@pytest.mark.asyncio +async def test_list_security_settings_async_pages(): + client = SecuritySettingsServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token="abc", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], next_page_token="def", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[security_settings.SecuritySettings(),], + next_page_token="ghi", + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_security_settings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_security_settings( + transport: str = "grpc", + request_type=security_settings.DeleteSecuritySettingsRequest, +): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == security_settings.DeleteSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_security_settings_from_dict(): + test_delete_security_settings(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_security_settings_async( + transport: str = "grpc_asyncio", + request_type=security_settings.DeleteSecuritySettingsRequest, +): + client = SecuritySettingsServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == security_settings.DeleteSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_security_settings_async_from_dict(): + await test_delete_security_settings_async(request_type=dict) + + +def test_delete_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=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 = security_settings.DeleteSecuritySettingsRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), "__call__" + ) as call: + call.return_value = None + + client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=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 = security_settings.DeleteSecuritySettingsRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_security_settings(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_delete_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_security_settings(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] + + assert args[0].name == "name_value" + + +def test_delete_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_security_settings( + security_settings.DeleteSecuritySettingsRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_security_settings(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] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_security_settings( + security_settings.DeleteSecuritySettingsRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecuritySettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecuritySettingsServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = SecuritySettingsServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecuritySettingsServiceGrpcTransport, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, transports.SecuritySettingsServiceGrpcTransport, + ) + + +def test_security_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.SecuritySettingsServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_security_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SecuritySettingsServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_security_settings", + "get_security_settings", + "update_security_settings", + "list_security_settings", + "delete_security_settings", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_security_settings_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.SecuritySettingsServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_security_settings_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.SecuritySettingsServiceTransport() + adc.assert_called_once() + + +def test_security_settings_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + SecuritySettingsServiceClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +def test_security_settings_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.SecuritySettingsServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_security_settings_service_host_no_port(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_security_settings_service_host_with_port(): + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:8000" + + +def test_security_settings_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.SecuritySettingsServiceGrpcTransport( + 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_security_settings_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecuritySettingsServiceGrpcTransport, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + ], +) +def test_security_settings_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", autospec=True + ) 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 = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + 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 + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecuritySettingsServiceGrpcTransport, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + ], +) +def test_security_settings_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", autospec=True + ) 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + 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_security_settings_path(): + project = "squid" + location = "clam" + security_settings = "whelk" + + expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( + project=project, location=location, security_settings=security_settings, + ) + actual = SecuritySettingsServiceClient.security_settings_path( + project, location, security_settings + ) + assert expected == actual + + +def test_parse_security_settings_path(): + expected = { + "project": "octopus", + "location": "oyster", + "security_settings": "nudibranch", + } + path = SecuritySettingsServiceClient.security_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_security_settings_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SecuritySettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SecuritySettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + + expected = "folders/{folder}".format(folder=folder,) + actual = SecuritySettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SecuritySettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + + expected = "organizations/{organization}".format(organization=organization,) + actual = SecuritySettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SecuritySettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + + expected = "projects/{project}".format(project=project,) + actual = SecuritySettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SecuritySettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = SecuritySettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SecuritySettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.SecuritySettingsServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SecuritySettingsServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SecuritySettingsServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SecuritySettingsServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info)