From 977e2aa9c17c235d125c633a6f4ba9f5a1dade7b Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 30 Sep 2021 09:34:28 +0000 Subject: [PATCH] feat(v3beta1): added support for Deployments with ListDeployments and GetDeployment apis (#177) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 399726267 Source-Link: https://github.com/googleapis/googleapis/commit/14829f3dc2bd29de58dad4ca0fe116d1c9114a49 Source-Link: https://github.com/googleapis/googleapis-gen/commit/bba746f8fc7494254decabce122582ad1a717958 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYmJhNzQ2ZjhmYzc0OTQyNTRkZWNhYmNlMTIyNTgyYWQxYTcxNzk1OCJ9 feat(v3beta1): added support for DeployFlow api under Environments feat(v3beta1): added support for TestCasesConfig under Environment docs(v3beta1): added long running operation explanation for several apis fix(v3beta1): marked resource name of security setting as not-required --- docs/dialogflowcx_v3beta1/deployments.rst | 10 + docs/dialogflowcx_v3beta1/services.rst | 1 + google/cloud/dialogflowcx_v3beta1/__init__.py | 18 + .../dialogflowcx_v3beta1/gapic_metadata.json | 44 + .../services/agents/async_client.py | 15 +- .../services/agents/client.py | 15 +- .../services/agents/transports/grpc.py | 15 +- .../agents/transports/grpc_asyncio.py | 15 +- .../services/deployments/__init__.py | 22 + .../services/deployments/async_client.py | 344 ++++ .../services/deployments/client.py | 595 ++++++ .../services/deployments/pagers.py | 155 ++ .../deployments/transports/__init__.py | 33 + .../services/deployments/transports/base.py | 190 ++ .../services/deployments/transports/grpc.py | 286 +++ .../deployments/transports/grpc_asyncio.py | 290 +++ .../services/environments/async_client.py | 106 + .../services/environments/client.py | 121 ++ .../services/environments/transports/base.py | 12 + .../services/environments/transports/grpc.py | 67 + .../environments/transports/grpc_asyncio.py | 67 + .../services/flows/async_client.py | 35 +- .../services/flows/client.py | 35 +- .../services/flows/transports/grpc.py | 35 +- .../services/flows/transports/grpc_asyncio.py | 35 +- .../services/test_cases/async_client.py | 48 +- .../services/test_cases/client.py | 48 +- .../services/test_cases/transports/grpc.py | 48 +- .../test_cases/transports/grpc_asyncio.py | 48 +- .../services/versions/async_client.py | 23 +- .../services/versions/client.py | 23 +- .../services/versions/transports/grpc.py | 23 +- .../versions/transports/grpc_asyncio.py | 23 +- .../dialogflowcx_v3beta1/types/__init__.py | 16 + .../dialogflowcx_v3beta1/types/deployment.py | 155 ++ .../dialogflowcx_v3beta1/types/environment.py | 78 + .../types/security_settings.py | 6 +- .../dialogflowcx_v3beta1/types/test_case.py | 2 +- .../dialogflowcx_v3beta1/test_deployments.py | 1723 +++++++++++++++++ .../dialogflowcx_v3beta1/test_environments.py | 215 +- 40 files changed, 4953 insertions(+), 87 deletions(-) create mode 100644 docs/dialogflowcx_v3beta1/deployments.rst create mode 100644 google/cloud/dialogflowcx_v3beta1/services/deployments/__init__.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/deployments/client.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/deployments/pagers.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/deployments/transports/__init__.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc.py create mode 100644 google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py create mode 100644 google/cloud/dialogflowcx_v3beta1/types/deployment.py create mode 100644 tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py diff --git a/docs/dialogflowcx_v3beta1/deployments.rst b/docs/dialogflowcx_v3beta1/deployments.rst new file mode 100644 index 00000000..53b2aeaf --- /dev/null +++ b/docs/dialogflowcx_v3beta1/deployments.rst @@ -0,0 +1,10 @@ +Deployments +----------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.deployments + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.deployments.pagers + :members: + :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/services.rst b/docs/dialogflowcx_v3beta1/services.rst index 03f147db..b12e93b2 100644 --- a/docs/dialogflowcx_v3beta1/services.rst +++ b/docs/dialogflowcx_v3beta1/services.rst @@ -4,6 +4,7 @@ Services for Google Cloud Dialogflowcx v3beta1 API :maxdepth: 2 agents + deployments entity_types environments experiments diff --git a/google/cloud/dialogflowcx_v3beta1/__init__.py b/google/cloud/dialogflowcx_v3beta1/__init__.py index 6ce4a51b..f404f8ff 100644 --- a/google/cloud/dialogflowcx_v3beta1/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/__init__.py @@ -16,6 +16,8 @@ from .services.agents import AgentsClient from .services.agents import AgentsAsyncClient +from .services.deployments import DeploymentsClient +from .services.deployments import DeploymentsAsyncClient from .services.entity_types import EntityTypesClient from .services.entity_types import EntityTypesAsyncClient from .services.environments import EnvironmentsClient @@ -67,6 +69,10 @@ from .types.audio_config import OutputAudioEncoding from .types.audio_config import SpeechModelVariant from .types.audio_config import SsmlVoiceGender +from .types.deployment import Deployment +from .types.deployment import GetDeploymentRequest +from .types.deployment import ListDeploymentsRequest +from .types.deployment import ListDeploymentsResponse from .types.entity_type import CreateEntityTypeRequest from .types.entity_type import DeleteEntityTypeRequest from .types.entity_type import EntityType @@ -77,6 +83,9 @@ from .types.environment import ContinuousTestResult from .types.environment import CreateEnvironmentRequest from .types.environment import DeleteEnvironmentRequest +from .types.environment import DeployFlowMetadata +from .types.environment import DeployFlowRequest +from .types.environment import DeployFlowResponse from .types.environment import Environment from .types.environment import GetEnvironmentRequest from .types.environment import ListContinuousTestResultsRequest @@ -237,6 +246,7 @@ __all__ = ( "AgentsAsyncClient", + "DeploymentsAsyncClient", "EntityTypesAsyncClient", "EnvironmentsAsyncClient", "ExperimentsAsyncClient", @@ -290,6 +300,11 @@ "DeleteTransitionRouteGroupRequest", "DeleteVersionRequest", "DeleteWebhookRequest", + "DeployFlowMetadata", + "DeployFlowRequest", + "DeployFlowResponse", + "Deployment", + "DeploymentsClient", "DetectIntentRequest", "DetectIntentResponse", "DtmfInput", @@ -317,6 +332,7 @@ "Fulfillment", "GetAgentRequest", "GetAgentValidationResultRequest", + "GetDeploymentRequest", "GetEntityTypeRequest", "GetEnvironmentRequest", "GetExperimentRequest", @@ -346,6 +362,8 @@ "ListAgentsResponse", "ListContinuousTestResultsRequest", "ListContinuousTestResultsResponse", + "ListDeploymentsRequest", + "ListDeploymentsResponse", "ListEntityTypesRequest", "ListEntityTypesResponse", "ListEnvironmentsRequest", diff --git a/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json b/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json index 661610d7..4225947d 100644 --- a/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json +++ b/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json @@ -109,6 +109,40 @@ } } }, + "Deployments": { + "clients": { + "grpc": { + "libraryClient": "DeploymentsClient", + "rpcs": { + "GetDeployment": { + "methods": [ + "get_deployment" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DeploymentsAsyncClient", + "rpcs": { + "GetDeployment": { + "methods": [ + "get_deployment" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + } + } + } + } + }, "EntityTypes": { "clients": { "grpc": { @@ -188,6 +222,11 @@ "delete_environment" ] }, + "DeployFlow": { + "methods": [ + "deploy_flow" + ] + }, "GetEnvironment": { "methods": [ "get_environment" @@ -233,6 +272,11 @@ "delete_environment" ] }, + "DeployFlow": { + "methods": [ + "deploy_flow" + ] + }, "GetEnvironment": { "methods": [ "get_environment" diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py index a927c973..e3830859 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py @@ -608,8 +608,9 @@ async def export_agent( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Exports the specified agent to a binary file. This method is a - `long-running + r"""Exports the specified agent to a binary file. + + This method is a `long-running operation `__. The returned ``Operation`` type has the following method-specific fields: @@ -684,6 +685,16 @@ async def restore_agent( existing resources in agent (e.g. intents, entity types, flows) will be removed. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/client.py b/google/cloud/dialogflowcx_v3beta1/services/agents/client.py index 8522c68d..2603ce7d 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/client.py @@ -873,8 +873,9 @@ def export_agent( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Exports the specified agent to a binary file. This method is a - `long-running + r"""Exports the specified agent to a binary file. + + This method is a `long-running operation `__. The returned ``Operation`` type has the following method-specific fields: @@ -950,6 +951,16 @@ def restore_agent( existing resources in agent (e.g. intents, entity types, flows) will be removed. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py index 9ca06b42..a74df193 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py @@ -386,8 +386,9 @@ def export_agent( ) -> Callable[[agent.ExportAgentRequest], operations_pb2.Operation]: r"""Return a callable for the export agent method over gRPC. - Exports the specified agent to a binary file. This method is a - `long-running + Exports the specified agent to a binary file. + + This method is a `long-running operation `__. The returned ``Operation`` type has the following method-specific fields: @@ -427,6 +428,16 @@ def restore_agent( existing resources in agent (e.g. intents, entity types, flows) will be removed. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py index dddee692..f65f0fb5 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py @@ -393,8 +393,9 @@ def export_agent( ) -> Callable[[agent.ExportAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the export agent method over gRPC. - Exports the specified agent to a binary file. This method is a - `long-running + Exports the specified agent to a binary file. + + This method is a `long-running operation `__. The returned ``Operation`` type has the following method-specific fields: @@ -434,6 +435,16 @@ def restore_agent( existing resources in agent (e.g. intents, entity types, flows) will be removed. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/__init__.py new file mode 100644 index 00000000..59dd17bb --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 DeploymentsClient +from .async_client import DeploymentsAsyncClient + +__all__ = ( + "DeploymentsClient", + "DeploymentsAsyncClient", +) diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py new file mode 100644 index 00000000..3a743c8b --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py @@ -0,0 +1,344 @@ +# -*- 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 as core_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 as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3beta1.services.deployments import pagers +from google.cloud.dialogflowcx_v3beta1.types import deployment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DeploymentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DeploymentsGrpcAsyncIOTransport +from .client import DeploymentsClient + + +class DeploymentsAsyncClient: + """Service for managing + [Deployments][google.cloud.dialogflow.cx.v3beta1.Deployment]. + """ + + _client: DeploymentsClient + + DEFAULT_ENDPOINT = DeploymentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DeploymentsClient.DEFAULT_MTLS_ENDPOINT + + deployment_path = staticmethod(DeploymentsClient.deployment_path) + parse_deployment_path = staticmethod(DeploymentsClient.parse_deployment_path) + experiment_path = staticmethod(DeploymentsClient.experiment_path) + parse_experiment_path = staticmethod(DeploymentsClient.parse_experiment_path) + test_case_result_path = staticmethod(DeploymentsClient.test_case_result_path) + parse_test_case_result_path = staticmethod( + DeploymentsClient.parse_test_case_result_path + ) + version_path = staticmethod(DeploymentsClient.version_path) + parse_version_path = staticmethod(DeploymentsClient.parse_version_path) + common_billing_account_path = staticmethod( + DeploymentsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + DeploymentsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(DeploymentsClient.common_folder_path) + parse_common_folder_path = staticmethod(DeploymentsClient.parse_common_folder_path) + common_organization_path = staticmethod(DeploymentsClient.common_organization_path) + parse_common_organization_path = staticmethod( + DeploymentsClient.parse_common_organization_path + ) + common_project_path = staticmethod(DeploymentsClient.common_project_path) + parse_common_project_path = staticmethod( + DeploymentsClient.parse_common_project_path + ) + common_location_path = staticmethod(DeploymentsClient.common_location_path) + parse_common_location_path = staticmethod( + DeploymentsClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DeploymentsAsyncClient: The constructed client. + """ + return DeploymentsClient.from_service_account_info.__func__(DeploymentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DeploymentsAsyncClient: The constructed client. + """ + return DeploymentsClient.from_service_account_file.__func__(DeploymentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DeploymentsTransport: + """Returns the transport used by the client instance. + + Returns: + DeploymentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(DeploymentsClient).get_transport_class, type(DeploymentsClient) + ) + + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, DeploymentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the deployments 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, ~.DeploymentsTransport]): 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 = DeploymentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_deployments( + self, + request: deployment.ListDeploymentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDeploymentsAsyncPager: + r"""Returns the list of all deployments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsRequest`): + The request object. The request message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3beta1.Deployments.ListDeployments]. + 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: + google.cloud.dialogflowcx_v3beta1.services.deployments.pagers.ListDeploymentsAsyncPager: + The response message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3beta1.Deployments.ListDeployments]. + + 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 = deployment.ListDeploymentsRequest(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_deployments, + 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.ListDeploymentsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_deployment( + self, + request: deployment.GetDeploymentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> deployment.Deployment: + r"""Retrieves the specified + [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetDeploymentRequest`): + The request object. The request message for + [Deployments.GetDeployment][google.cloud.dialogflow.cx.v3beta1.Deployments.GetDeployment]. + name (:class:`str`): + Required. The name of the + [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. + Format: + ``projects//locations//agents//environments//deployments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Deployment: + Represents an deployment in an + environment. A deployment happens when a + flow version configured to be active in + the environment. You can configure + running pre-deployment steps, e.g. + running validation test cases, + experiment auto-rollout, etc. + + """ + # 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 = deployment.GetDeploymentRequest(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_deployment, + 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__ = ("DeploymentsAsyncClient",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py new file mode 100644 index 00000000..e1d772b6 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py @@ -0,0 +1,595 @@ +# -*- 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 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 as core_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 as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3beta1.services.deployments import pagers +from google.cloud.dialogflowcx_v3beta1.types import deployment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DeploymentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DeploymentsGrpcTransport +from .transports.grpc_asyncio import DeploymentsGrpcAsyncIOTransport + + +class DeploymentsClientMeta(type): + """Metaclass for the Deployments 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[DeploymentsTransport]] + _transport_registry["grpc"] = DeploymentsGrpcTransport + _transport_registry["grpc_asyncio"] = DeploymentsGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[DeploymentsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class DeploymentsClient(metaclass=DeploymentsClientMeta): + """Service for managing + [Deployments][google.cloud.dialogflow.cx.v3beta1.Deployment]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DeploymentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DeploymentsClient: 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) -> DeploymentsTransport: + """Returns the transport used by the client instance. + + Returns: + DeploymentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def deployment_path( + project: str, location: str, agent: str, environment: str, deployment: str, + ) -> str: + """Returns a fully-qualified deployment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/deployments/{deployment}".format( + project=project, + location=location, + agent=agent, + environment=environment, + deployment=deployment, + ) + + @staticmethod + def parse_deployment_path(path: str) -> Dict[str, str]: + """Parses a deployment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/deployments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def experiment_path( + project: str, location: str, agent: str, environment: str, experiment: str, + ) -> str: + """Returns 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]: + """Parses 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 test_case_result_path( + project: str, location: str, agent: str, test_case: str, result: str, + ) -> str: + """Returns a fully-qualified test_case_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( + project=project, + location=location, + agent=agent, + test_case=test_case, + result=result, + ) + + @staticmethod + def parse_test_case_result_path(path: str) -> Dict[str, str]: + """Parses a test_case_result path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def version_path( + project: str, location: str, agent: str, flow: str, version: str, + ) -> str: + """Returns 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]: + """Parses 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: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DeploymentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the deployments 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, DeploymentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_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")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = 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": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = 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, DeploymentsTransport): + # transport is a DeploymentsTransport 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, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def list_deployments( + self, + request: Union[deployment.ListDeploymentsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDeploymentsPager: + r"""Returns the list of all deployments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsRequest, dict]): + The request object. The request message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3beta1.Deployments.ListDeployments]. + parent (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: + google.cloud.dialogflowcx_v3beta1.services.deployments.pagers.ListDeploymentsPager: + The response message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3beta1.Deployments.ListDeployments]. + + 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 deployment.ListDeploymentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, deployment.ListDeploymentsRequest): + request = deployment.ListDeploymentsRequest(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_deployments] + + # 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.ListDeploymentsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_deployment( + self, + request: Union[deployment.GetDeploymentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> deployment.Deployment: + r"""Retrieves the specified + [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetDeploymentRequest, dict]): + The request object. The request message for + [Deployments.GetDeployment][google.cloud.dialogflow.cx.v3beta1.Deployments.GetDeployment]. + name (str): + Required. The name of the + [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. + Format: + ``projects//locations//agents//environments//deployments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Deployment: + Represents an deployment in an + environment. A deployment happens when a + flow version configured to be active in + the environment. You can configure + running pre-deployment steps, e.g. + running validation test cases, + experiment auto-rollout, etc. + + """ + # 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 deployment.GetDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, deployment.GetDeploymentRequest): + request = deployment.GetDeploymentRequest(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_deployment] + + # 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__ = ("DeploymentsClient",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/pagers.py new file mode 100644 index 00000000..6cd0384c --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/pagers.py @@ -0,0 +1,155 @@ +# -*- 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, + Optional, +) + +from google.cloud.dialogflowcx_v3beta1.types import deployment + + +class ListDeploymentsPager: + """A pager for iterating through ``list_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``deployments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDeployments`` requests and continue to iterate + through the ``deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsResponse` + 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[..., deployment.ListDeploymentsResponse], + request: deployment.ListDeploymentsRequest, + response: deployment.ListDeploymentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsResponse): + 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 = deployment.ListDeploymentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[deployment.ListDeploymentsResponse]: + 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[deployment.Deployment]: + for page in self.pages: + yield from page.deployments + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDeploymentsAsyncPager: + """A pager for iterating through ``list_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``deployments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDeployments`` requests and continue to iterate + through the ``deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsResponse` + 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[deployment.ListDeploymentsResponse]], + request: deployment.ListDeploymentsRequest, + response: deployment.ListDeploymentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsResponse): + 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 = deployment.ListDeploymentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[deployment.ListDeploymentsResponse]: + 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[deployment.Deployment]: + async def async_generator(): + async for page in self.pages: + for response in page.deployments: + 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/deployments/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/__init__.py new file mode 100644 index 00000000..78292dd3 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- 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 DeploymentsTransport +from .grpc import DeploymentsGrpcTransport +from .grpc_asyncio import DeploymentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DeploymentsTransport]] +_transport_registry["grpc"] = DeploymentsGrpcTransport +_transport_registry["grpc_asyncio"] = DeploymentsGrpcAsyncIOTransport + +__all__ = ( + "DeploymentsTransport", + "DeploymentsGrpcTransport", + "DeploymentsGrpcAsyncIOTransport", +) diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py new file mode 100644 index 00000000..5d3acfde --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py @@ -0,0 +1,190 @@ +# -*- 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_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 as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import deployment + +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() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class DeploymentsTransport(abc.ABC): + """Abstract transport class for Deployments.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_deployments: gapic_v1.method.wrap_method( + self.list_deployments, default_timeout=None, client_info=client_info, + ), + self.get_deployment: gapic_v1.method.wrap_method( + self.get_deployment, default_timeout=None, client_info=client_info, + ), + } + + @property + def list_deployments( + self, + ) -> Callable[ + [deployment.ListDeploymentsRequest], + Union[ + deployment.ListDeploymentsResponse, + Awaitable[deployment.ListDeploymentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_deployment( + self, + ) -> Callable[ + [deployment.GetDeploymentRequest], + Union[deployment.Deployment, Awaitable[deployment.Deployment]], + ]: + raise NotImplementedError() + + +__all__ = ("DeploymentsTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc.py new file mode 100644 index 00000000..6a638325 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc.py @@ -0,0 +1,286 @@ +# -*- 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, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import deployment +from .base import DeploymentsTransport, DEFAULT_CLIENT_INFO + + +class DeploymentsGrpcTransport(DeploymentsTransport): + """gRPC backend transport for Deployments. + + Service for managing + [Deployments][google.cloud.dialogflow.cx.v3beta1.Deployment]. + + 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: ga_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, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_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: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_deployments( + self, + ) -> Callable[ + [deployment.ListDeploymentsRequest], deployment.ListDeploymentsResponse + ]: + r"""Return a callable for the list deployments method over gRPC. + + Returns the list of all deployments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.ListDeploymentsRequest], + ~.ListDeploymentsResponse]: + 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_deployments" not in self._stubs: + self._stubs["list_deployments"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Deployments/ListDeployments", + request_serializer=deployment.ListDeploymentsRequest.serialize, + response_deserializer=deployment.ListDeploymentsResponse.deserialize, + ) + return self._stubs["list_deployments"] + + @property + def get_deployment( + self, + ) -> Callable[[deployment.GetDeploymentRequest], deployment.Deployment]: + r"""Return a callable for the get deployment method over gRPC. + + Retrieves the specified + [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. + + Returns: + Callable[[~.GetDeploymentRequest], + ~.Deployment]: + 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_deployment" not in self._stubs: + self._stubs["get_deployment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Deployments/GetDeployment", + request_serializer=deployment.GetDeploymentRequest.serialize, + response_deserializer=deployment.Deployment.deserialize, + ) + return self._stubs["get_deployment"] + + +__all__ = ("DeploymentsGrpcTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py new file mode 100644 index 00000000..360eb457 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py @@ -0,0 +1,290 @@ +# -*- 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, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import deployment +from .base import DeploymentsTransport, DEFAULT_CLIENT_INFO +from .grpc import DeploymentsGrpcTransport + + +class DeploymentsGrpcAsyncIOTransport(DeploymentsTransport): + """gRPC AsyncIO backend transport for Deployments. + + Service for managing + [Deployments][google.cloud.dialogflow.cx.v3beta1.Deployment]. + + 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_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, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_deployments( + self, + ) -> Callable[ + [deployment.ListDeploymentsRequest], + Awaitable[deployment.ListDeploymentsResponse], + ]: + r"""Return a callable for the list deployments method over gRPC. + + Returns the list of all deployments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.ListDeploymentsRequest], + Awaitable[~.ListDeploymentsResponse]]: + 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_deployments" not in self._stubs: + self._stubs["list_deployments"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Deployments/ListDeployments", + request_serializer=deployment.ListDeploymentsRequest.serialize, + response_deserializer=deployment.ListDeploymentsResponse.deserialize, + ) + return self._stubs["list_deployments"] + + @property + def get_deployment( + self, + ) -> Callable[[deployment.GetDeploymentRequest], Awaitable[deployment.Deployment]]: + r"""Return a callable for the get deployment method over gRPC. + + Retrieves the specified + [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. + + Returns: + Callable[[~.GetDeploymentRequest], + Awaitable[~.Deployment]]: + 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_deployment" not in self._stubs: + self._stubs["get_deployment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Deployments/GetDeployment", + request_serializer=deployment.GetDeploymentRequest.serialize, + response_deserializer=deployment.Deployment.deserialize, + ) + return self._stubs["get_deployment"] + + +__all__ = ("DeploymentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py index dc94b16b..5f76bc0f 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py @@ -57,6 +57,8 @@ class EnvironmentsAsyncClient: ) environment_path = staticmethod(EnvironmentsClient.environment_path) parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) + test_case_path = staticmethod(EnvironmentsClient.test_case_path) + parse_test_case_path = staticmethod(EnvironmentsClient.parse_test_case_path) test_case_result_path = staticmethod(EnvironmentsClient.test_case_result_path) parse_test_case_result_path = staticmethod( EnvironmentsClient.parse_test_case_result_path @@ -361,6 +363,16 @@ async def create_environment( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateEnvironmentRequest`): The request object. The request message for @@ -464,6 +476,16 @@ async def update_environment( r"""Updates the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateEnvironmentRequest`): The request object. The request message for @@ -712,6 +734,16 @@ async def run_continuous_test( r"""Kicks off a continuous test under the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunContinuousTestMetadata][google.cloud.dialogflow.cx.v3beta1.RunContinuousTestMetadata] + - ``response``: + [RunContinuousTestResponse][google.cloud.dialogflow.cx.v3beta1.RunContinuousTestResponse] + Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestRequest`): The request object. The request message for @@ -846,6 +878,80 @@ async def list_continuous_test_results( # Done; return the response. return response + async def deploy_flow( + self, + request: environment.DeployFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deploys a flow to the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [DeployFlowMetadata][google.cloud.dialogflow.cx.v3beta1.DeployFlowMetadata] + - ``response``: + [DeployFlowResponse][google.cloud.dialogflow.cx.v3beta1.DeployFlowResponse] + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeployFlowRequest`): + The request object. The request message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3beta1.Environments.DeployFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.DeployFlowResponse` + The response message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3beta1.Environments.DeployFlow]. + + """ + # Create or coerce a protobuf request object. + request = environment.DeployFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.deploy_flow, + 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( + (("environment", request.environment),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + environment.DeployFlowResponse, + metadata_type=environment.DeployFlowMetadata, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/client.py b/google/cloud/dialogflowcx_v3beta1/services/environments/client.py index 3d3ffc65..18db0dd0 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/client.py @@ -205,6 +205,22 @@ def parse_environment_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def test_case_path(project: str, location: str, agent: str, test_case: str,) -> str: + """Returns a fully-qualified test_case string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format( + project=project, location=location, agent=agent, test_case=test_case, + ) + + @staticmethod + def parse_test_case_path(path: str) -> Dict[str, str]: + """Parses a test_case path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def test_case_result_path( project: str, location: str, agent: str, test_case: str, result: str, @@ -608,6 +624,16 @@ def create_environment( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + Args: request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateEnvironmentRequest, dict]): The request object. The request message for @@ -711,6 +737,16 @@ def update_environment( r"""Updates the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + Args: request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateEnvironmentRequest, dict]): The request object. The request message for @@ -961,6 +997,16 @@ def run_continuous_test( r"""Kicks off a continuous test under the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunContinuousTestMetadata][google.cloud.dialogflow.cx.v3beta1.RunContinuousTestMetadata] + - ``response``: + [RunContinuousTestResponse][google.cloud.dialogflow.cx.v3beta1.RunContinuousTestResponse] + Args: request (Union[google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestRequest, dict]): The request object. The request message for @@ -1098,6 +1144,81 @@ def list_continuous_test_results( # Done; return the response. return response + def deploy_flow( + self, + request: Union[environment.DeployFlowRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deploys a flow to the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [DeployFlowMetadata][google.cloud.dialogflow.cx.v3beta1.DeployFlowMetadata] + - ``response``: + [DeployFlowResponse][google.cloud.dialogflow.cx.v3beta1.DeployFlowResponse] + + Args: + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeployFlowRequest, dict]): + The request object. The request message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3beta1.Environments.DeployFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.DeployFlowResponse` + The response message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3beta1.Environments.DeployFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeployFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeployFlowRequest): + request = environment.DeployFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.deploy_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("environment", request.environment),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + environment.DeployFlowResponse, + metadata_type=environment.DeployFlowMetadata, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py index ab43720e..63e9ae4f 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py @@ -189,6 +189,9 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.deploy_flow: gapic_v1.method.wrap_method( + self.deploy_flow, default_timeout=None, client_info=client_info, + ), } @property @@ -277,5 +280,14 @@ def list_continuous_test_results( ]: raise NotImplementedError() + @property + def deploy_flow( + self, + ) -> Callable[ + [environment.DeployFlowRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + __all__ = ("EnvironmentsTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py index 9f007ffa..3259ee27 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py @@ -313,6 +313,16 @@ def create_environment( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + Returns: Callable[[~.CreateEnvironmentRequest], ~.Operation]: @@ -342,6 +352,16 @@ def update_environment( Updates the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + Returns: Callable[[~.UpdateEnvironmentRequest], ~.Operation]: @@ -426,6 +446,16 @@ def run_continuous_test( Kicks off a continuous test under the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunContinuousTestMetadata][google.cloud.dialogflow.cx.v3beta1.RunContinuousTestMetadata] + - ``response``: + [RunContinuousTestResponse][google.cloud.dialogflow.cx.v3beta1.RunContinuousTestResponse] + Returns: Callable[[~.RunContinuousTestRequest], ~.Operation]: @@ -474,5 +504,42 @@ def list_continuous_test_results( ) return self._stubs["list_continuous_test_results"] + @property + def deploy_flow( + self, + ) -> Callable[[environment.DeployFlowRequest], operations_pb2.Operation]: + r"""Return a callable for the deploy flow method over gRPC. + + Deploys a flow to the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [DeployFlowMetadata][google.cloud.dialogflow.cx.v3beta1.DeployFlowMetadata] + - ``response``: + [DeployFlowResponse][google.cloud.dialogflow.cx.v3beta1.DeployFlowResponse] + + Returns: + Callable[[~.DeployFlowRequest], + ~.Operation]: + 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 "deploy_flow" not in self._stubs: + self._stubs["deploy_flow"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Environments/DeployFlow", + request_serializer=environment.DeployFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["deploy_flow"] + __all__ = ("EnvironmentsGrpcTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py index 4b13fdd9..69d6971f 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py @@ -321,6 +321,16 @@ def create_environment( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + Returns: Callable[[~.CreateEnvironmentRequest], Awaitable[~.Operation]]: @@ -350,6 +360,16 @@ def update_environment( Updates the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + Returns: Callable[[~.UpdateEnvironmentRequest], Awaitable[~.Operation]]: @@ -436,6 +456,16 @@ def run_continuous_test( Kicks off a continuous test under the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunContinuousTestMetadata][google.cloud.dialogflow.cx.v3beta1.RunContinuousTestMetadata] + - ``response``: + [RunContinuousTestResponse][google.cloud.dialogflow.cx.v3beta1.RunContinuousTestResponse] + Returns: Callable[[~.RunContinuousTestRequest], Awaitable[~.Operation]]: @@ -484,5 +514,42 @@ def list_continuous_test_results( ) return self._stubs["list_continuous_test_results"] + @property + def deploy_flow( + self, + ) -> Callable[[environment.DeployFlowRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the deploy flow method over gRPC. + + Deploys a flow to the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [DeployFlowMetadata][google.cloud.dialogflow.cx.v3beta1.DeployFlowMetadata] + - ``response``: + [DeployFlowResponse][google.cloud.dialogflow.cx.v3beta1.DeployFlowResponse] + + Returns: + Callable[[~.DeployFlowRequest], + Awaitable[~.Operation]]: + 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 "deploy_flow" not in self._stubs: + self._stubs["deploy_flow"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Environments/DeployFlow", + request_serializer=environment.DeployFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["deploy_flow"] + __all__ = ("EnvironmentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py index eed8cb70..d3b0b78d 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py @@ -635,6 +635,16 @@ async def train_flow( r"""Trains the specified flow. Note that only the flow in 'draft' environment is trained. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. @@ -855,6 +865,16 @@ async def import_flow( r"""Imports the specified flow to the specified agent from a binary file. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ImportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ImportFlowResponse] + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. @@ -919,8 +939,19 @@ async def export_flow( metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ExportFlowResponse] + + Note that resources (e.g. intents, entities, webhooks) that the + flow references will also be exported. Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowRequest`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/client.py b/google/cloud/dialogflowcx_v3beta1/services/flows/client.py index 7d93adaf..65e3f7cb 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/client.py @@ -908,6 +908,16 @@ def train_flow( r"""Trains the specified flow. Note that only the flow in 'draft' environment is trained. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. @@ -1131,6 +1141,16 @@ def import_flow( r"""Imports the specified flow to the specified agent from a binary file. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ImportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ImportFlowResponse] + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. @@ -1196,8 +1216,19 @@ def export_flow( metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ExportFlowResponse] + + Note that resources (e.g. intents, entities, webhooks) that the + flow references will also be exported. Args: request (Union[google.cloud.dialogflowcx_v3beta1.types.ExportFlowRequest, dict]): diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py index 0dcb359e..90cc95f0 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py @@ -380,6 +380,16 @@ def train_flow(self) -> Callable[[flow.TrainFlowRequest], operations_pb2.Operati Trains the specified flow. Note that only the flow in 'draft' environment is trained. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. @@ -467,6 +477,16 @@ def import_flow( Imports the specified flow to the specified agent from a binary file. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ImportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ImportFlowResponse] + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. @@ -496,8 +516,19 @@ def export_flow( r"""Return a callable for the export flow method over gRPC. Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ExportFlowResponse] + + Note that resources (e.g. intents, entities, webhooks) that the + flow references will also be exported. Returns: Callable[[~.ExportFlowRequest], diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py index a573f358..92fa87a5 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py @@ -395,6 +395,16 @@ def train_flow( Trains the specified flow. Note that only the flow in 'draft' environment is trained. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. @@ -484,6 +494,16 @@ def import_flow( Imports the specified flow to the specified agent from a binary file. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ImportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ImportFlowResponse] + Note: You should always train a flow prior to sending it queries. See the `training documentation `__. @@ -513,8 +533,19 @@ def export_flow( r"""Return a callable for the export flow method over gRPC. Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ExportFlowResponse] + + Note that resources (e.g. intents, entities, webhooks) that the + flow references will also be exported. Returns: Callable[[~.ExportFlowRequest], diff --git a/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py index 01d98a12..3c07b07f 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py @@ -568,7 +568,9 @@ async def run_test_case( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Kicks off a test case run. This method is a `long-running + r"""Kicks off a test case run. + + This method is a `long-running operation `__. The returned ``Operation`` type has the following method-specific fields: @@ -639,6 +641,16 @@ async def batch_run_test_cases( ) -> operation_async.AsyncOperation: r"""Kicks off a batch run of test cases. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [BatchRunTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesMetadata] + - ``response``: + [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesResponse] + Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesRequest`): The request object. The request message for @@ -747,10 +759,20 @@ async def import_test_cases( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. + r"""Imports the test cases from a Cloud Storage bucket or a local + file. It always creates new test cases and won't overwite any + existing ones. The provided ID in the imported test case is + neglected. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ImportTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesMetadata] + - ``response``: + [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesResponse] Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesRequest`): @@ -811,9 +833,19 @@ async def export_test_cases( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. + r"""Exports the test cases under the agent to a Cloud Storage bucket + or a local file. Filter can be applied to export a subset of + test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ExportTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesMetadata] + - ``response``: + [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesResponse] Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py b/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py index 473be451..c2780c4e 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py @@ -899,7 +899,9 @@ def run_test_case( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Kicks off a test case run. This method is a `long-running + r"""Kicks off a test case run. + + This method is a `long-running operation `__. The returned ``Operation`` type has the following method-specific fields: @@ -971,6 +973,16 @@ def batch_run_test_cases( ) -> operation.Operation: r"""Kicks off a batch run of test cases. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [BatchRunTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesMetadata] + - ``response``: + [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesResponse] + Args: request (Union[google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesRequest, dict]): The request object. The request message for @@ -1081,10 +1093,20 @@ def import_test_cases( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. + r"""Imports the test cases from a Cloud Storage bucket or a local + file. It always creates new test cases and won't overwite any + existing ones. The provided ID in the imported test case is + neglected. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ImportTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesMetadata] + - ``response``: + [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesResponse] Args: request (Union[google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesRequest, dict]): @@ -1146,9 +1168,19 @@ def export_test_cases( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. + r"""Exports the test cases under the agent to a Cloud Storage bucket + or a local file. Filter can be applied to export a subset of + test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ExportTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesMetadata] + - ``response``: + [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesResponse] Args: request (Union[google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest, dict]): diff --git a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py index d4fd4a3d..dff7156a 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py @@ -382,7 +382,9 @@ def run_test_case( ) -> Callable[[test_case.RunTestCaseRequest], operations_pb2.Operation]: r"""Return a callable for the run test case method over gRPC. - Kicks off a test case run. This method is a `long-running + Kicks off a test case run. + + This method is a `long-running operation `__. The returned ``Operation`` type has the following method-specific fields: @@ -418,6 +420,16 @@ def batch_run_test_cases( Kicks off a batch run of test cases. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [BatchRunTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesMetadata] + - ``response``: + [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesResponse] + Returns: Callable[[~.BatchRunTestCasesRequest], ~.Operation]: @@ -470,10 +482,20 @@ def import_test_cases( ) -> Callable[[test_case.ImportTestCasesRequest], operations_pb2.Operation]: r"""Return a callable for the import test cases method over gRPC. - Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. + Imports the test cases from a Cloud Storage bucket or a local + file. It always creates new test cases and won't overwite any + existing ones. The provided ID in the imported test case is + neglected. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ImportTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesMetadata] + - ``response``: + [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesResponse] Returns: Callable[[~.ImportTestCasesRequest], @@ -499,9 +521,19 @@ def export_test_cases( ) -> Callable[[test_case.ExportTestCasesRequest], operations_pb2.Operation]: r"""Return a callable for the export test cases method over gRPC. - Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. + Exports the test cases under the agent to a Cloud Storage bucket + or a local file. Filter can be applied to export a subset of + test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ExportTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesMetadata] + - ``response``: + [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesResponse] Returns: Callable[[~.ExportTestCasesRequest], diff --git a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py index 04c29c8a..457abc7d 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py @@ -393,7 +393,9 @@ def run_test_case( ) -> Callable[[test_case.RunTestCaseRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the run test case method over gRPC. - Kicks off a test case run. This method is a `long-running + Kicks off a test case run. + + This method is a `long-running operation `__. The returned ``Operation`` type has the following method-specific fields: @@ -431,6 +433,16 @@ def batch_run_test_cases( Kicks off a batch run of test cases. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [BatchRunTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesMetadata] + - ``response``: + [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesResponse] + Returns: Callable[[~.BatchRunTestCasesRequest], Awaitable[~.Operation]]: @@ -486,10 +498,20 @@ def import_test_cases( ]: r"""Return a callable for the import test cases method over gRPC. - Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. + Imports the test cases from a Cloud Storage bucket or a local + file. It always creates new test cases and won't overwite any + existing ones. The provided ID in the imported test case is + neglected. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ImportTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesMetadata] + - ``response``: + [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesResponse] Returns: Callable[[~.ImportTestCasesRequest], @@ -517,9 +539,19 @@ def export_test_cases( ]: r"""Return a callable for the export test cases method over gRPC. - Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. + Exports the test cases under the agent to a Cloud Storage bucket + or a local file. Filter can be applied to export a subset of + test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ExportTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesMetadata] + - ``response``: + [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesResponse] Returns: Callable[[~.ExportTestCasesRequest], diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py index 0cde3c6d..2ab1aaf1 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py @@ -332,6 +332,16 @@ async def create_version( in the specified [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [CreateVersionOperationMetadata][google.cloud.dialogflow.cx.v3beta1.CreateVersionOperationMetadata] + - ``response``: + [Version][google.cloud.dialogflow.cx.v3beta1.Version] + Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateVersionRequest`): The request object. The request message for @@ -571,8 +581,17 @@ async def load_version( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Loads resources in the specified version to the draft - flow. + r"""Loads resources in the specified version to the draft flow. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.LoadVersionRequest`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/client.py b/google/cloud/dialogflowcx_v3beta1/services/versions/client.py index 7b5e5ca7..6a7cc7b2 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/client.py @@ -529,6 +529,16 @@ def create_version( in the specified [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [CreateVersionOperationMetadata][google.cloud.dialogflow.cx.v3beta1.CreateVersionOperationMetadata] + - ``response``: + [Version][google.cloud.dialogflow.cx.v3beta1.Version] + Args: request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateVersionRequest, dict]): The request object. The request message for @@ -768,8 +778,17 @@ def load_version( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Loads resources in the specified version to the draft - flow. + r"""Loads resources in the specified version to the draft flow. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ Args: request (Union[google.cloud.dialogflowcx_v3beta1.types.LoadVersionRequest, dict]): diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py index ff78ec16..192860ea 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py @@ -307,6 +307,16 @@ def create_version( in the specified [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [CreateVersionOperationMetadata][google.cloud.dialogflow.cx.v3beta1.CreateVersionOperationMetadata] + - ``response``: + [Version][google.cloud.dialogflow.cx.v3beta1.Version] + Returns: Callable[[~.CreateVersionRequest], ~.Operation]: @@ -385,8 +395,17 @@ def load_version( ) -> Callable[[version.LoadVersionRequest], operations_pb2.Operation]: r"""Return a callable for the load version method over gRPC. - Loads resources in the specified version to the draft - flow. + Loads resources in the specified version to the draft flow. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ Returns: Callable[[~.LoadVersionRequest], diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py index a161444b..04c5efe3 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py @@ -318,6 +318,16 @@ def create_version( in the specified [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [CreateVersionOperationMetadata][google.cloud.dialogflow.cx.v3beta1.CreateVersionOperationMetadata] + - ``response``: + [Version][google.cloud.dialogflow.cx.v3beta1.Version] + Returns: Callable[[~.CreateVersionRequest], Awaitable[~.Operation]]: @@ -396,8 +406,17 @@ def load_version( ) -> Callable[[version.LoadVersionRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the load version method over gRPC. - Loads resources in the specified version to the draft - flow. + Loads resources in the specified version to the draft flow. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ Returns: Callable[[~.LoadVersionRequest], diff --git a/google/cloud/dialogflowcx_v3beta1/types/__init__.py b/google/cloud/dialogflowcx_v3beta1/types/__init__.py index b0518a2d..b81c76bd 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/types/__init__.py @@ -41,6 +41,12 @@ SpeechModelVariant, SsmlVoiceGender, ) +from .deployment import ( + Deployment, + GetDeploymentRequest, + ListDeploymentsRequest, + ListDeploymentsResponse, +) from .entity_type import ( CreateEntityTypeRequest, DeleteEntityTypeRequest, @@ -54,6 +60,9 @@ ContinuousTestResult, CreateEnvironmentRequest, DeleteEnvironmentRequest, + DeployFlowMetadata, + DeployFlowRequest, + DeployFlowResponse, Environment, GetEnvironmentRequest, ListContinuousTestResultsRequest, @@ -262,6 +271,10 @@ "OutputAudioEncoding", "SpeechModelVariant", "SsmlVoiceGender", + "Deployment", + "GetDeploymentRequest", + "ListDeploymentsRequest", + "ListDeploymentsResponse", "CreateEntityTypeRequest", "DeleteEntityTypeRequest", "EntityType", @@ -272,6 +285,9 @@ "ContinuousTestResult", "CreateEnvironmentRequest", "DeleteEnvironmentRequest", + "DeployFlowMetadata", + "DeployFlowRequest", + "DeployFlowResponse", "Environment", "GetEnvironmentRequest", "ListContinuousTestResultsRequest", diff --git a/google/cloud/dialogflowcx_v3beta1/types/deployment.py b/google/cloud/dialogflowcx_v3beta1/types/deployment.py new file mode 100644 index 00000000..032ce3a7 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/types/deployment.py @@ -0,0 +1,155 @@ +# -*- 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3beta1", + manifest={ + "Deployment", + "ListDeploymentsRequest", + "ListDeploymentsResponse", + "GetDeploymentRequest", + }, +) + + +class Deployment(proto.Message): + r"""Represents an deployment in an environment. A deployment + happens when a flow version configured to be active in the + environment. You can configure running pre-deployment steps, + e.g. running validation test cases, experiment auto-rollout, + etc. + + Attributes: + name (str): + The name of the deployment. + Format: projects//locations//agents//environments//deployments/. + flow_version (str): + The name of the flow version for this + deployment. Format: projects//locations//agents//flows//versions/. + state (google.cloud.dialogflowcx_v3beta1.types.Deployment.State): + The current state of the deployment. + result (google.cloud.dialogflowcx_v3beta1.types.Deployment.Result): + Result of the deployment. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of this deployment. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of this deployment. + """ + + class State(proto.Enum): + r"""The state of the deployment.""" + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + + class Result(proto.Message): + r"""Result of the deployment. + Attributes: + deployment_test_results (Sequence[str]): + Results of test cases running before the deployment. Format: + ``projects//locations//agents//testCases//results/``. + experiment (str): + The name of the experiment triggered by this + deployment. Format: projects//locations//agents//environments//experiments/. + """ + + deployment_test_results = proto.RepeatedField(proto.STRING, number=1,) + experiment = proto.Field(proto.STRING, number=2,) + + name = proto.Field(proto.STRING, number=1,) + flow_version = proto.Field(proto.STRING, number=2,) + state = proto.Field(proto.ENUM, number=3, enum=State,) + result = proto.Field(proto.MESSAGE, number=4, message=Result,) + start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) + + +class ListDeploymentsRequest(proto.Message): + r"""The request message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3beta1.Deployments.ListDeployments]. + + 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 ListDeploymentsResponse(proto.Message): + r"""The response message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3beta1.Deployments.ListDeployments]. + + Attributes: + deployments (Sequence[google.cloud.dialogflowcx_v3beta1.types.Deployment]): + The list of deployments. 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 + + deployments = proto.RepeatedField(proto.MESSAGE, number=1, message="Deployment",) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetDeploymentRequest(proto.Message): + r"""The request message for + [Deployments.GetDeployment][google.cloud.dialogflow.cx.v3beta1.Deployments.GetDeployment]. + + Attributes: + name (str): + Required. The name of the + [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. + Format: + ``projects//locations//agents//environments//deployments/``. + """ + + name = proto.Field(proto.STRING, number=1,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/environment.py b/google/cloud/dialogflowcx_v3beta1/types/environment.py index 4d47818d..1985d1bd 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/environment.py +++ b/google/cloud/dialogflowcx_v3beta1/types/environment.py @@ -38,6 +38,9 @@ "RunContinuousTestMetadata", "ListContinuousTestResultsRequest", "ListContinuousTestResultsResponse", + "DeployFlowRequest", + "DeployFlowResponse", + "DeployFlowMetadata", }, ) @@ -73,6 +76,9 @@ class Environment(proto.Message): agent. Otherwise, an error will be returned. update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. Update time of this environment. + test_cases_config (google.cloud.dialogflowcx_v3beta1.types.Environment.TestCasesConfig): + The test cases config for continuous tests of + this environment. """ class VersionConfig(proto.Message): @@ -86,6 +92,28 @@ class VersionConfig(proto.Message): version = proto.Field(proto.STRING, number=1,) + class TestCasesConfig(proto.Message): + r"""The configuration for continuous tests. + Attributes: + test_cases (Sequence[str]): + A list of test case names to run. They should be under the + same agent. Format of each test case name: + ``projects//locations/ /agents//testCases/`` + enable_continuous_run (bool): + Whether to run test cases in + [TestCasesConfig.test_cases][google.cloud.dialogflow.cx.v3beta1.Environment.TestCasesConfig.test_cases] + periodically. Default false. If set to true, run once a day. + enable_predeployment_run (bool): + Whether to run test cases in + [TestCasesConfig.test_cases][google.cloud.dialogflow.cx.v3beta1.Environment.TestCasesConfig.test_cases] + before deploying a flow version to the environment. Default + false. + """ + + test_cases = proto.RepeatedField(proto.STRING, number=1,) + enable_continuous_run = proto.Field(proto.BOOL, number=2,) + enable_predeployment_run = proto.Field(proto.BOOL, number=3,) + name = proto.Field(proto.STRING, number=1,) display_name = proto.Field(proto.STRING, number=2,) description = proto.Field(proto.STRING, number=3,) @@ -93,6 +121,7 @@ class VersionConfig(proto.Message): proto.MESSAGE, number=6, message=VersionConfig, ) update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + test_cases_config = proto.Field(proto.MESSAGE, number=7, message=TestCasesConfig,) class ListEnvironmentsRequest(proto.Message): @@ -370,4 +399,53 @@ def raw_page(self): next_page_token = proto.Field(proto.STRING, number=2,) +class DeployFlowRequest(proto.Message): + r"""The request message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3beta1.Environments.DeployFlow]. + + Attributes: + environment (str): + Required. The environment to deploy the flow to. Format: + ``projects//locations//agents// environments/``. + flow_version (str): + Required. The flow version to deploy. Format: + ``projects//locations//agents// flows//versions/``. + """ + + environment = proto.Field(proto.STRING, number=1,) + flow_version = proto.Field(proto.STRING, number=2,) + + +class DeployFlowResponse(proto.Message): + r"""The response message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3beta1.Environments.DeployFlow]. + + Attributes: + environment (google.cloud.dialogflowcx_v3beta1.types.Environment): + The updated environment where the flow is + deployed. + deployment (str): + The name of the flow version deployment. Format: + ``projects//locations//agents// environments//deployments/``. + """ + + environment = proto.Field(proto.MESSAGE, number=1, message="Environment",) + deployment = proto.Field(proto.STRING, number=2,) + + +class DeployFlowMetadata(proto.Message): + r"""Metadata returned for the + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3beta1.Environments.DeployFlow] + long running operation. + + Attributes: + test_errors (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestError]): + Errors of running deployment tests. + """ + + test_errors = proto.RepeatedField( + proto.MESSAGE, number=1, message=test_case.TestError, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/security_settings.py b/google/cloud/dialogflowcx_v3beta1/types/security_settings.py index 4cefe4be..ea10c838 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/security_settings.py +++ b/google/cloud/dialogflowcx_v3beta1/types/security_settings.py @@ -146,7 +146,11 @@ class SecuritySettings(proto.Message): Attributes: name (str): - Required. Resource name of the settings. Format: + Resource name of the settings. Required for the + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings] + method. + [SecuritySettingsService.CreateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.CreateSecuritySettings] + populates the name automatically. Format: ``projects//locations//securitySettings/``. display_name (str): Required. The human-readable name of the diff --git a/google/cloud/dialogflowcx_v3beta1/types/test_case.py b/google/cloud/dialogflowcx_v3beta1/types/test_case.py index 6ae129db..c1deab19 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/test_case.py +++ b/google/cloud/dialogflowcx_v3beta1/types/test_case.py @@ -858,7 +858,7 @@ class ExportTestCasesResponse(proto.Message): class ExportTestCasesMetadata(proto.Message): r"""Metadata returned for the [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases] - long running operation. + long running operation. This message currently has no fields. """ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py new file mode 100644 index 00000000..c879e323 --- /dev/null +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py @@ -0,0 +1,1723 @@ +# -*- 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 packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflowcx_v3beta1.services.deployments import ( + DeploymentsAsyncClient, +) +from google.cloud.dialogflowcx_v3beta1.services.deployments import DeploymentsClient +from google.cloud.dialogflowcx_v3beta1.services.deployments import pagers +from google.cloud.dialogflowcx_v3beta1.services.deployments import transports +from google.cloud.dialogflowcx_v3beta1.services.deployments.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.dialogflowcx_v3beta1.types import deployment +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + + +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 DeploymentsClient._get_default_mtls_endpoint(None) is None + assert ( + DeploymentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + DeploymentsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + DeploymentsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + DeploymentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert DeploymentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [DeploymentsClient, DeploymentsAsyncClient,]) +def test_deployments_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.DeploymentsGrpcTransport, "grpc"), + (transports.DeploymentsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_deployments_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [DeploymentsClient, DeploymentsAsyncClient,]) +def test_deployments_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_deployments_client_get_transport_class(): + transport = DeploymentsClient.get_transport_class() + available_transports = [ + transports.DeploymentsGrpcTransport, + ] + assert transport in available_transports + + transport = DeploymentsClient.get_transport_class("grpc") + assert transport == transports.DeploymentsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DeploymentsClient, transports.DeploymentsGrpcTransport, "grpc"), + ( + DeploymentsAsyncClient, + transports.DeploymentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + DeploymentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeploymentsClient) +) +@mock.patch.object( + DeploymentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DeploymentsAsyncClient), +) +def test_deployments_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(DeploymentsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(DeploymentsClient, "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, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (DeploymentsClient, transports.DeploymentsGrpcTransport, "grpc", "true"), + ( + DeploymentsAsyncClient, + transports.DeploymentsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (DeploymentsClient, transports.DeploymentsGrpcTransport, "grpc", "false"), + ( + DeploymentsAsyncClient, + transports.DeploymentsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + DeploymentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeploymentsClient) +) +@mock.patch.object( + DeploymentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DeploymentsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_deployments_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DeploymentsClient, transports.DeploymentsGrpcTransport, "grpc"), + ( + DeploymentsAsyncClient, + transports.DeploymentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_deployments_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"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DeploymentsClient, transports.DeploymentsGrpcTransport, "grpc"), + ( + DeploymentsAsyncClient, + transports.DeploymentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_deployments_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, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_deployments_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.deployments.transports.DeploymentsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = DeploymentsClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_deployments( + transport: str = "grpc", request_type=deployment.ListDeploymentsRequest +): + client = DeploymentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = deployment.ListDeploymentsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == deployment.ListDeploymentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeploymentsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_deployments_from_dict(): + test_list_deployments(request_type=dict) + + +def test_list_deployments_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeploymentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + client.list_deployments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == deployment.ListDeploymentsRequest() + + +@pytest.mark.asyncio +async def test_list_deployments_async( + transport: str = "grpc_asyncio", request_type=deployment.ListDeploymentsRequest +): + client = DeploymentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + deployment.ListDeploymentsResponse(next_page_token="next_page_token_value",) + ) + response = await client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == deployment.ListDeploymentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeploymentsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_deployments_async_from_dict(): + await test_list_deployments_async(request_type=dict) + + +def test_list_deployments_field_headers(): + client = DeploymentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = deployment.ListDeploymentsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + call.return_value = deployment.ListDeploymentsResponse() + client.list_deployments(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_deployments_field_headers_async(): + client = DeploymentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = deployment.ListDeploymentsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + deployment.ListDeploymentsResponse() + ) + await client.list_deployments(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_deployments_flattened(): + client = DeploymentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = deployment.ListDeploymentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_deployments(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_deployments_flattened_error(): + client = DeploymentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_deployments( + deployment.ListDeploymentsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_deployments_flattened_async(): + client = DeploymentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = deployment.ListDeploymentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + deployment.ListDeploymentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_deployments(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_deployments_flattened_error_async(): + client = DeploymentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_deployments( + deployment.ListDeploymentsRequest(), parent="parent_value", + ) + + +def test_list_deployments_pager(): + client = DeploymentsClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + deployment.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + deployment.Deployment(), + ], + next_page_token="abc", + ), + deployment.ListDeploymentsResponse(deployments=[], next_page_token="def",), + deployment.ListDeploymentsResponse( + deployments=[deployment.Deployment(),], next_page_token="ghi", + ), + deployment.ListDeploymentsResponse( + deployments=[deployment.Deployment(), deployment.Deployment(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_deployments(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, deployment.Deployment) for i in results) + + +def test_list_deployments_pages(): + client = DeploymentsClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + deployment.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + deployment.Deployment(), + ], + next_page_token="abc", + ), + deployment.ListDeploymentsResponse(deployments=[], next_page_token="def",), + deployment.ListDeploymentsResponse( + deployments=[deployment.Deployment(),], next_page_token="ghi", + ), + deployment.ListDeploymentsResponse( + deployments=[deployment.Deployment(), deployment.Deployment(),], + ), + RuntimeError, + ) + pages = list(client.list_deployments(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_deployments_async_pager(): + client = DeploymentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + deployment.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + deployment.Deployment(), + ], + next_page_token="abc", + ), + deployment.ListDeploymentsResponse(deployments=[], next_page_token="def",), + deployment.ListDeploymentsResponse( + deployments=[deployment.Deployment(),], next_page_token="ghi", + ), + deployment.ListDeploymentsResponse( + deployments=[deployment.Deployment(), deployment.Deployment(),], + ), + RuntimeError, + ) + async_pager = await client.list_deployments(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, deployment.Deployment) for i in responses) + + +@pytest.mark.asyncio +async def test_list_deployments_async_pages(): + client = DeploymentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + deployment.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + deployment.Deployment(), + ], + next_page_token="abc", + ), + deployment.ListDeploymentsResponse(deployments=[], next_page_token="def",), + deployment.ListDeploymentsResponse( + deployments=[deployment.Deployment(),], next_page_token="ghi", + ), + deployment.ListDeploymentsResponse( + deployments=[deployment.Deployment(), deployment.Deployment(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_deployments(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_deployment( + transport: str = "grpc", request_type=deployment.GetDeploymentRequest +): + client = DeploymentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = deployment.Deployment( + name="name_value", + flow_version="flow_version_value", + state=deployment.Deployment.State.RUNNING, + ) + response = client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == deployment.GetDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, deployment.Deployment) + assert response.name == "name_value" + assert response.flow_version == "flow_version_value" + assert response.state == deployment.Deployment.State.RUNNING + + +def test_get_deployment_from_dict(): + test_get_deployment(request_type=dict) + + +def test_get_deployment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeploymentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + client.get_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == deployment.GetDeploymentRequest() + + +@pytest.mark.asyncio +async def test_get_deployment_async( + transport: str = "grpc_asyncio", request_type=deployment.GetDeploymentRequest +): + client = DeploymentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + deployment.Deployment( + name="name_value", + flow_version="flow_version_value", + state=deployment.Deployment.State.RUNNING, + ) + ) + response = await client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == deployment.GetDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, deployment.Deployment) + assert response.name == "name_value" + assert response.flow_version == "flow_version_value" + assert response.state == deployment.Deployment.State.RUNNING + + +@pytest.mark.asyncio +async def test_get_deployment_async_from_dict(): + await test_get_deployment_async(request_type=dict) + + +def test_get_deployment_field_headers(): + client = DeploymentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = deployment.GetDeploymentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + call.return_value = deployment.Deployment() + client.get_deployment(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_deployment_field_headers_async(): + client = DeploymentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = deployment.GetDeploymentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + deployment.Deployment() + ) + await client.get_deployment(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_deployment_flattened(): + client = DeploymentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = deployment.Deployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_deployment(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_deployment_flattened_error(): + client = DeploymentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_deployment( + deployment.GetDeploymentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_deployment_flattened_async(): + client = DeploymentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = deployment.Deployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + deployment.Deployment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_deployment(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_deployment_flattened_error_async(): + client = DeploymentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_deployment( + deployment.GetDeploymentRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DeploymentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeploymentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DeploymentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeploymentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DeploymentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeploymentsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeploymentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DeploymentsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeploymentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DeploymentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [transports.DeploymentsGrpcTransport, transports.DeploymentsGrpcAsyncIOTransport,], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DeploymentsClient(credentials=ga_credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.DeploymentsGrpcTransport,) + + +def test_deployments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DeploymentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_deployments_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.deployments.transports.DeploymentsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.DeploymentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_deployments", + "get_deployment", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_deployments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.deployments.transports.DeploymentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DeploymentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_deployments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.deployments.transports.DeploymentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DeploymentsTransport( + 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_deployments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.deployments.transports.DeploymentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DeploymentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_deployments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DeploymentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_deployments_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DeploymentsClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.DeploymentsGrpcTransport, transports.DeploymentsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_deployments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.DeploymentsGrpcTransport, transports.DeploymentsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_deployments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DeploymentsGrpcTransport, grpc_helpers), + (transports.DeploymentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_deployments_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.DeploymentsGrpcTransport, transports.DeploymentsGrpcAsyncIOTransport], +) +def test_deployments_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_deployments_host_no_port(): + client = DeploymentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_deployments_host_with_port(): + client = DeploymentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:8000" + + +def test_deployments_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DeploymentsGrpcTransport( + 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_deployments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DeploymentsGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.DeploymentsGrpcTransport, transports.DeploymentsGrpcAsyncIOTransport], +) +def test_deployments_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.DeploymentsGrpcTransport, transports.DeploymentsGrpcAsyncIOTransport], +) +def test_deployments_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_deployment_path(): + project = "squid" + location = "clam" + agent = "whelk" + environment = "octopus" + deployment = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/deployments/{deployment}".format( + project=project, + location=location, + agent=agent, + environment=environment, + deployment=deployment, + ) + actual = DeploymentsClient.deployment_path( + project, location, agent, environment, deployment + ) + assert expected == actual + + +def test_parse_deployment_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "environment": "winkle", + "deployment": "nautilus", + } + path = DeploymentsClient.deployment_path(**expected) + + # Check that the path construction is reversible. + actual = DeploymentsClient.parse_deployment_path(path) + assert expected == actual + + +def test_experiment_path(): + project = "scallop" + location = "abalone" + agent = "squid" + environment = "clam" + experiment = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format( + project=project, + location=location, + agent=agent, + environment=environment, + experiment=experiment, + ) + actual = DeploymentsClient.experiment_path( + project, location, agent, environment, experiment + ) + assert expected == actual + + +def test_parse_experiment_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "environment": "cuttlefish", + "experiment": "mussel", + } + path = DeploymentsClient.experiment_path(**expected) + + # Check that the path construction is reversible. + actual = DeploymentsClient.parse_experiment_path(path) + assert expected == actual + + +def test_test_case_result_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + test_case = "abalone" + result = "squid" + expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( + project=project, + location=location, + agent=agent, + test_case=test_case, + result=result, + ) + actual = DeploymentsClient.test_case_result_path( + project, location, agent, test_case, result + ) + assert expected == actual + + +def test_parse_test_case_result_path(): + expected = { + "project": "clam", + "location": "whelk", + "agent": "octopus", + "test_case": "oyster", + "result": "nudibranch", + } + path = DeploymentsClient.test_case_result_path(**expected) + + # Check that the path construction is reversible. + actual = DeploymentsClient.parse_test_case_result_path(path) + assert expected == actual + + +def test_version_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + flow = "nautilus" + version = "scallop" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( + project=project, location=location, agent=agent, flow=flow, version=version, + ) + actual = DeploymentsClient.version_path(project, location, agent, flow, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "abalone", + "location": "squid", + "agent": "clam", + "flow": "whelk", + "version": "octopus", + } + path = DeploymentsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = DeploymentsClient.parse_version_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = DeploymentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = DeploymentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DeploymentsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder,) + actual = DeploymentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = DeploymentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DeploymentsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization,) + actual = DeploymentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = DeploymentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DeploymentsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project,) + actual = DeploymentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = DeploymentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DeploymentsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = DeploymentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = DeploymentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DeploymentsClient.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.DeploymentsTransport, "_prep_wrapped_messages" + ) as prep: + client = DeploymentsClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.DeploymentsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = DeploymentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py index f7b3e538..937a51c7 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py @@ -2611,6 +2611,136 @@ async def test_list_continuous_test_results_async_pages(): assert page_.raw_page.next_page_token == token +def test_deploy_flow( + transport: str = "grpc", request_type=environment.DeployFlowRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.deploy_flow), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.deploy_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeployFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_deploy_flow_from_dict(): + test_deploy_flow(request_type=dict) + + +def test_deploy_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.deploy_flow), "__call__") as call: + client.deploy_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeployFlowRequest() + + +@pytest.mark.asyncio +async def test_deploy_flow_async( + transport: str = "grpc_asyncio", request_type=environment.DeployFlowRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.deploy_flow), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.deploy_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeployFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_deploy_flow_async_from_dict(): + await test_deploy_flow_async(request_type=dict) + + +def test_deploy_flow_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeployFlowRequest() + + request.environment = "environment/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.deploy_flow), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.deploy_flow(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", "environment=environment/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_deploy_flow_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeployFlowRequest() + + request.environment = "environment/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.deploy_flow), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.deploy_flow(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", "environment=environment/value",) in kw["metadata"] + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.EnvironmentsGrpcTransport( @@ -2716,6 +2846,7 @@ def test_environments_base_transport(): "lookup_environment_history", "run_continuous_test", "list_continuous_test_results", + "deploy_flow", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3165,12 +3296,38 @@ def test_parse_environment_path(): assert expected == actual -def test_test_case_result_path(): +def test_test_case_path(): project = "cuttlefish" location = "mussel" agent = "winkle" test_case = "nautilus" - result = "scallop" + expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format( + project=project, location=location, agent=agent, test_case=test_case, + ) + actual = EnvironmentsClient.test_case_path(project, location, agent, test_case) + assert expected == actual + + +def test_parse_test_case_path(): + expected = { + "project": "scallop", + "location": "abalone", + "agent": "squid", + "test_case": "clam", + } + path = EnvironmentsClient.test_case_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_test_case_path(path) + assert expected == actual + + +def test_test_case_result_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + test_case = "nudibranch" + result = "cuttlefish" expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( project=project, location=location, @@ -3186,11 +3343,11 @@ def test_test_case_result_path(): def test_parse_test_case_result_path(): expected = { - "project": "abalone", - "location": "squid", - "agent": "clam", - "test_case": "whelk", - "result": "octopus", + "project": "mussel", + "location": "winkle", + "agent": "nautilus", + "test_case": "scallop", + "result": "abalone", } path = EnvironmentsClient.test_case_result_path(**expected) @@ -3200,11 +3357,11 @@ def test_parse_test_case_result_path(): def test_version_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - flow = "mussel" - version = "winkle" + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + version = "oyster" expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @@ -3214,11 +3371,11 @@ def test_version_path(): def test_parse_version_path(): expected = { - "project": "nautilus", - "location": "scallop", - "agent": "abalone", - "flow": "squid", - "version": "clam", + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "flow": "winkle", + "version": "nautilus", } path = EnvironmentsClient.version_path(**expected) @@ -3228,7 +3385,7 @@ def test_parse_version_path(): def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3238,7 +3395,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "abalone", } path = EnvironmentsClient.common_billing_account_path(**expected) @@ -3248,7 +3405,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "squid" expected = "folders/{folder}".format(folder=folder,) actual = EnvironmentsClient.common_folder_path(folder) assert expected == actual @@ -3256,7 +3413,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "clam", } path = EnvironmentsClient.common_folder_path(**expected) @@ -3266,7 +3423,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "whelk" expected = "organizations/{organization}".format(organization=organization,) actual = EnvironmentsClient.common_organization_path(organization) assert expected == actual @@ -3274,7 +3431,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "octopus", } path = EnvironmentsClient.common_organization_path(**expected) @@ -3284,7 +3441,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "oyster" expected = "projects/{project}".format(project=project,) actual = EnvironmentsClient.common_project_path(project) assert expected == actual @@ -3292,7 +3449,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "nudibranch", } path = EnvironmentsClient.common_project_path(**expected) @@ -3302,8 +3459,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3313,8 +3470,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "winkle", + "location": "nautilus", } path = EnvironmentsClient.common_location_path(**expected)