diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 7d98291c..cb89b2e3 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:58f73ba196b5414782605236dd0712a73541b44ff2ff4d3a36ec41092dd6fa5b + digest: sha256:ec49167c606648a063d1222220b48119c912562849a0528f35bfb592a9f72737 diff --git a/.kokoro/docs/common.cfg b/.kokoro/docs/common.cfg index 07f0586c..559ca309 100644 --- a/.kokoro/docs/common.cfg +++ b/.kokoro/docs/common.cfg @@ -30,6 +30,7 @@ env_vars: { env_vars: { key: "V2_STAGING_BUCKET" + # Push google cloud library docs to the Cloud RAD bucket `docs-staging-v2` value: "docs-staging-v2" } diff --git a/.repo-metadata.json b/.repo-metadata.json index f15d4f3d..699a5021 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -9,6 +9,7 @@ "library_type": "GAPIC_AUTO", "repo": "googleapis/python-dialogflow-cx", "distribution_name": "google-cloud-dialogflow-cx", - "api_id": "dialogflow.googleapis.com" - } - \ No newline at end of file + "api_id": "dialogflow.googleapis.com", + "default_version": "v3", + "codeowner_team": "" +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f14d08d..102d8339 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog +## [1.6.0](https://www.github.com/googleapis/python-dialogflow-cx/compare/v1.5.0...v1.6.0) (2021-11-05) + + +### Features + +* add support for python 3.10 ([#192](https://www.github.com/googleapis/python-dialogflow-cx/issues/192)) ([527b679](https://www.github.com/googleapis/python-dialogflow-cx/commit/527b679286ce7ed6481bf5c9258858473ca1f601)) +* **v3:** added API for changelogs ([#197](https://www.github.com/googleapis/python-dialogflow-cx/issues/197)) ([4f41653](https://www.github.com/googleapis/python-dialogflow-cx/commit/4f41653b08a5be4aa6c871f285d941a2f43740a9)) +* **v3beta1:** added API for changelogs ([#198](https://www.github.com/googleapis/python-dialogflow-cx/issues/198)) ([484e13a](https://www.github.com/googleapis/python-dialogflow-cx/commit/484e13a78830a3d0ce8b1745fdf2dfce0f88a21e)) +* **v3beta1:** added support for comparing between versions ([#202](https://www.github.com/googleapis/python-dialogflow-cx/issues/202)) ([b8e16f8](https://www.github.com/googleapis/python-dialogflow-cx/commit/b8e16f8a17a49c1fc65f7f4392e33fb273bcd8ca)) + + +### Bug Fixes + +* **deps:** drop packaging dependency ([c44582e](https://www.github.com/googleapis/python-dialogflow-cx/commit/c44582e2fe3d49327bb0fc5ba05d2959b6965b7b)) +* **deps:** require google-api-core >= 1.28.0 ([c44582e](https://www.github.com/googleapis/python-dialogflow-cx/commit/c44582e2fe3d49327bb0fc5ba05d2959b6965b7b)) + + +### Documentation + +* list oneofs in docstring ([c44582e](https://www.github.com/googleapis/python-dialogflow-cx/commit/c44582e2fe3d49327bb0fc5ba05d2959b6965b7b)) +* **samples:** add voice selection ([#184](https://www.github.com/googleapis/python-dialogflow-cx/issues/184)) ([778b86f](https://www.github.com/googleapis/python-dialogflow-cx/commit/778b86f69e88ceb884bb9933128d2b14c6689174)) +* **samples:** added webhook sample ([#169](https://www.github.com/googleapis/python-dialogflow-cx/issues/169)) ([74cfc9a](https://www.github.com/googleapis/python-dialogflow-cx/commit/74cfc9a7ab9b85fa05565c406534a3cd3391ab4f)) +* **samples:** adds list training phrases sample ([#196](https://www.github.com/googleapis/python-dialogflow-cx/issues/196)) ([dfefa4e](https://www.github.com/googleapis/python-dialogflow-cx/commit/dfefa4e21bcd6bf37d341911187fab283152f514)) +* **v3beta1:** clarified security settings API reference ([b8e16f8](https://www.github.com/googleapis/python-dialogflow-cx/commit/b8e16f8a17a49c1fc65f7f4392e33fb273bcd8ca)) +* **v3:** clarified semantic of the streaming APIs ([4f41653](https://www.github.com/googleapis/python-dialogflow-cx/commit/4f41653b08a5be4aa6c871f285d941a2f43740a9)) + ## [1.5.0](https://www.github.com/googleapis/python-dialogflow-cx/compare/v1.4.0...v1.5.0) (2021-10-11) diff --git a/docs/dialogflowcx_v3/changelogs.rst b/docs/dialogflowcx_v3/changelogs.rst new file mode 100644 index 00000000..1f064c53 --- /dev/null +++ b/docs/dialogflowcx_v3/changelogs.rst @@ -0,0 +1,10 @@ +Changelogs +---------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.changelogs + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.changelogs.pagers + :members: + :inherited-members: diff --git a/docs/dialogflowcx_v3/services.rst b/docs/dialogflowcx_v3/services.rst index 0868cc62..6a19e426 100644 --- a/docs/dialogflowcx_v3/services.rst +++ b/docs/dialogflowcx_v3/services.rst @@ -4,6 +4,7 @@ Services for Google Cloud Dialogflowcx v3 API :maxdepth: 2 agents + changelogs deployments entity_types environments diff --git a/docs/dialogflowcx_v3beta1/changelogs.rst b/docs/dialogflowcx_v3beta1/changelogs.rst new file mode 100644 index 00000000..9fc3d9e1 --- /dev/null +++ b/docs/dialogflowcx_v3beta1/changelogs.rst @@ -0,0 +1,10 @@ +Changelogs +---------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.changelogs + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.changelogs.pagers + :members: + :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/services.rst b/docs/dialogflowcx_v3beta1/services.rst index b12e93b2..2029fb08 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 + changelogs deployments entity_types environments diff --git a/google/cloud/dialogflowcx/__init__.py b/google/cloud/dialogflowcx/__init__.py index 35deff7e..b7b8774f 100644 --- a/google/cloud/dialogflowcx/__init__.py +++ b/google/cloud/dialogflowcx/__init__.py @@ -16,6 +16,10 @@ from google.cloud.dialogflowcx_v3.services.agents.client import AgentsClient from google.cloud.dialogflowcx_v3.services.agents.async_client import AgentsAsyncClient +from google.cloud.dialogflowcx_v3.services.changelogs.client import ChangelogsClient +from google.cloud.dialogflowcx_v3.services.changelogs.async_client import ( + ChangelogsAsyncClient, +) from google.cloud.dialogflowcx_v3.services.deployments.client import DeploymentsClient from google.cloud.dialogflowcx_v3.services.deployments.async_client import ( DeploymentsAsyncClient, @@ -99,6 +103,10 @@ from google.cloud.dialogflowcx_v3.types.audio_config import OutputAudioEncoding from google.cloud.dialogflowcx_v3.types.audio_config import SpeechModelVariant from google.cloud.dialogflowcx_v3.types.audio_config import SsmlVoiceGender +from google.cloud.dialogflowcx_v3.types.changelog import Changelog +from google.cloud.dialogflowcx_v3.types.changelog import GetChangelogRequest +from google.cloud.dialogflowcx_v3.types.changelog import ListChangelogsRequest +from google.cloud.dialogflowcx_v3.types.changelog import ListChangelogsResponse from google.cloud.dialogflowcx_v3.types.deployment import Deployment from google.cloud.dialogflowcx_v3.types.deployment import GetDeploymentRequest from google.cloud.dialogflowcx_v3.types.deployment import ListDeploymentsRequest @@ -323,6 +331,8 @@ __all__ = ( "AgentsClient", "AgentsAsyncClient", + "ChangelogsClient", + "ChangelogsAsyncClient", "DeploymentsClient", "DeploymentsAsyncClient", "EntityTypesClient", @@ -375,6 +385,10 @@ "OutputAudioEncoding", "SpeechModelVariant", "SsmlVoiceGender", + "Changelog", + "GetChangelogRequest", + "ListChangelogsRequest", + "ListChangelogsResponse", "Deployment", "GetDeploymentRequest", "ListDeploymentsRequest", diff --git a/google/cloud/dialogflowcx_v3/__init__.py b/google/cloud/dialogflowcx_v3/__init__.py index f404f8ff..d3b5023c 100644 --- a/google/cloud/dialogflowcx_v3/__init__.py +++ b/google/cloud/dialogflowcx_v3/__init__.py @@ -16,6 +16,8 @@ from .services.agents import AgentsClient from .services.agents import AgentsAsyncClient +from .services.changelogs import ChangelogsClient +from .services.changelogs import ChangelogsAsyncClient from .services.deployments import DeploymentsClient from .services.deployments import DeploymentsAsyncClient from .services.entity_types import EntityTypesClient @@ -69,6 +71,10 @@ from .types.audio_config import OutputAudioEncoding from .types.audio_config import SpeechModelVariant from .types.audio_config import SsmlVoiceGender +from .types.changelog import Changelog +from .types.changelog import GetChangelogRequest +from .types.changelog import ListChangelogsRequest +from .types.changelog import ListChangelogsResponse from .types.deployment import Deployment from .types.deployment import GetDeploymentRequest from .types.deployment import ListDeploymentsRequest @@ -246,6 +252,7 @@ __all__ = ( "AgentsAsyncClient", + "ChangelogsAsyncClient", "DeploymentsAsyncClient", "EntityTypesAsyncClient", "EnvironmentsAsyncClient", @@ -272,6 +279,8 @@ "BatchRunTestCasesResponse", "CalculateCoverageRequest", "CalculateCoverageResponse", + "Changelog", + "ChangelogsClient", "ContinuousTestResult", "ConversationTurn", "CreateAgentRequest", @@ -332,6 +341,7 @@ "Fulfillment", "GetAgentRequest", "GetAgentValidationResultRequest", + "GetChangelogRequest", "GetDeploymentRequest", "GetEntityTypeRequest", "GetEnvironmentRequest", @@ -360,6 +370,8 @@ "IntentsClient", "ListAgentsRequest", "ListAgentsResponse", + "ListChangelogsRequest", + "ListChangelogsResponse", "ListContinuousTestResultsRequest", "ListContinuousTestResultsResponse", "ListDeploymentsRequest", diff --git a/google/cloud/dialogflowcx_v3/gapic_metadata.json b/google/cloud/dialogflowcx_v3/gapic_metadata.json index 49e71efa..0c7a85a1 100644 --- a/google/cloud/dialogflowcx_v3/gapic_metadata.json +++ b/google/cloud/dialogflowcx_v3/gapic_metadata.json @@ -109,6 +109,40 @@ } } }, + "Changelogs": { + "clients": { + "grpc": { + "libraryClient": "ChangelogsClient", + "rpcs": { + "GetChangelog": { + "methods": [ + "get_changelog" + ] + }, + "ListChangelogs": { + "methods": [ + "list_changelogs" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ChangelogsAsyncClient", + "rpcs": { + "GetChangelog": { + "methods": [ + "get_changelog" + ] + }, + "ListChangelogs": { + "methods": [ + "list_changelogs" + ] + } + } + } + } + }, "Deployments": { "clients": { "grpc": { diff --git a/google/cloud/dialogflowcx_v3/services/agents/async_client.py b/google/cloud/dialogflowcx_v3/services/agents/async_client.py index 6e77cf4f..6eebc13c 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/agents/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3.services.agents import pagers @@ -179,10 +181,10 @@ def __init__( async def list_agents( self, - request: agent.ListAgentsRequest = None, + request: Union[agent.ListAgentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListAgentsAsyncPager: @@ -190,7 +192,7 @@ async def list_agents( location. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListAgentsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListAgentsRequest, dict]): The request object. The request message for [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. parent (:class:`str`): @@ -260,17 +262,17 @@ async def list_agents( async def get_agent( self, - request: agent.GetAgentRequest = None, + request: Union[agent.GetAgentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.Agent: r"""Retrieves the specified agent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetAgentRequest, dict]): The request object. The request message for [Agents.GetAgent][google.cloud.dialogflow.cx.v3.Agents.GetAgent]. name (:class:`str`): @@ -343,11 +345,11 @@ async def get_agent( async def create_agent( self, - request: gcdc_agent.CreateAgentRequest = None, + request: Union[gcdc_agent.CreateAgentRequest, dict] = None, *, parent: str = None, agent: gcdc_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_agent.Agent: @@ -358,7 +360,7 @@ async def create_agent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateAgentRequest, dict]): The request object. The request message for [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent]. parent (:class:`str`): @@ -438,11 +440,11 @@ async def create_agent( async def update_agent( self, - request: gcdc_agent.UpdateAgentRequest = None, + request: Union[gcdc_agent.UpdateAgentRequest, dict] = None, *, agent: gcdc_agent.Agent = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_agent.Agent: @@ -453,7 +455,7 @@ async def update_agent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateAgentRequest, dict]): The request object. The request message for [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent]. agent (:class:`google.cloud.dialogflowcx_v3.types.Agent`): @@ -536,17 +538,17 @@ async def update_agent( async def delete_agent( self, - request: agent.DeleteAgentRequest = None, + request: Union[agent.DeleteAgentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified agent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteAgentRequest, dict]): The request object. The request message for [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3.Agents.DeleteAgent]. name (:class:`str`): @@ -600,9 +602,9 @@ async def delete_agent( async def export_agent( self, - request: agent.ExportAgentRequest = None, + request: Union[agent.ExportAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -619,7 +621,7 @@ async def export_agent( [ExportAgentResponse][google.cloud.dialogflow.cx.v3.ExportAgentResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ExportAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ExportAgentRequest, dict]): The request object. The request message for [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -671,9 +673,9 @@ async def export_agent( async def restore_agent( self, - request: agent.RestoreAgentRequest = None, + request: Union[agent.RestoreAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -698,7 +700,7 @@ async def restore_agent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.RestoreAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.RestoreAgentRequest, dict]): The request object. The request message for [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -759,9 +761,9 @@ async def restore_agent( async def validate_agent( self, - request: agent.ValidateAgentRequest = None, + request: Union[agent.ValidateAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.AgentValidationResult: @@ -771,7 +773,7 @@ async def validate_agent( completed to get the complete validation results. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ValidateAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ValidateAgentRequest, dict]): The request object. The request message for [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3.Agents.ValidateAgent]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -811,10 +813,10 @@ async def validate_agent( async def get_agent_validation_result( self, - request: agent.GetAgentValidationResultRequest = None, + request: Union[agent.GetAgentValidationResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.AgentValidationResult: @@ -822,7 +824,7 @@ async def get_agent_validation_result( validation is performed when ValidateAgent is called. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetAgentValidationResultRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetAgentValidationResultRequest, dict]): The request object. The request message for [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/agents/client.py b/google/cloud/dialogflowcx_v3/services/agents/client.py index 7b037191..0e21e239 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/client.py +++ b/google/cloud/dialogflowcx_v3/services/agents/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3.services.agents import pagers @@ -444,7 +446,7 @@ def list_agents( request: Union[agent.ListAgentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListAgentsPager: @@ -525,7 +527,7 @@ def get_agent( request: Union[agent.GetAgentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.Agent: @@ -609,7 +611,7 @@ def create_agent( *, parent: str = None, agent: gcdc_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_agent.Agent: @@ -704,7 +706,7 @@ def update_agent( *, agent: gcdc_agent.Agent = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_agent.Agent: @@ -801,7 +803,7 @@ def delete_agent( request: Union[agent.DeleteAgentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -864,7 +866,7 @@ def export_agent( self, request: Union[agent.ExportAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -936,7 +938,7 @@ def restore_agent( self, request: Union[agent.RestoreAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1025,7 +1027,7 @@ def validate_agent( self, request: Union[agent.ValidateAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.AgentValidationResult: @@ -1079,7 +1081,7 @@ def get_agent_validation_result( request: Union[agent.GetAgentValidationResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.AgentValidationResult: diff --git a/google/cloud/dialogflowcx_v3/services/agents/transports/base.py b/google/cloud/dialogflowcx_v3/services/agents/transports/base.py index 61b522a2..46960a28 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/agents/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 AgentsTransport(abc.ABC): """Abstract transport class for Agents.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { @@ -202,7 +169,7 @@ def close(self): raise NotImplementedError() @property - def operations_client(self) -> operations_v1.OperationsClient: + def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py index 68351cfa..063c1a31 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py @@ -114,7 +114,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py index a9708bf1..19d5fe2a 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py @@ -21,7 +21,6 @@ from google.api_core import operations_v1 # 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 @@ -161,7 +160,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3/services/changelogs/__init__.py b/google/cloud/dialogflowcx_v3/services/changelogs/__init__.py new file mode 100644 index 00000000..028672a9 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/changelogs/__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 ChangelogsClient +from .async_client import ChangelogsAsyncClient + +__all__ = ( + "ChangelogsClient", + "ChangelogsAsyncClient", +) diff --git a/google/cloud/dialogflowcx_v3/services/changelogs/async_client.py b/google/cloud/dialogflowcx_v3/services/changelogs/async_client.py new file mode 100644 index 00000000..8ba45547 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/changelogs/async_client.py @@ -0,0 +1,331 @@ +# -*- 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 + +from google.api_core.client_options import 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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.dialogflowcx_v3.services.changelogs import pagers +from google.cloud.dialogflowcx_v3.types import changelog +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ChangelogsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ChangelogsGrpcAsyncIOTransport +from .client import ChangelogsClient + + +class ChangelogsAsyncClient: + """Service for managing + [Changelogs][google.cloud.dialogflow.cx.v3.Changelog]. + """ + + _client: ChangelogsClient + + DEFAULT_ENDPOINT = ChangelogsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ChangelogsClient.DEFAULT_MTLS_ENDPOINT + + changelog_path = staticmethod(ChangelogsClient.changelog_path) + parse_changelog_path = staticmethod(ChangelogsClient.parse_changelog_path) + common_billing_account_path = staticmethod( + ChangelogsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ChangelogsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(ChangelogsClient.common_folder_path) + parse_common_folder_path = staticmethod(ChangelogsClient.parse_common_folder_path) + common_organization_path = staticmethod(ChangelogsClient.common_organization_path) + parse_common_organization_path = staticmethod( + ChangelogsClient.parse_common_organization_path + ) + common_project_path = staticmethod(ChangelogsClient.common_project_path) + parse_common_project_path = staticmethod(ChangelogsClient.parse_common_project_path) + common_location_path = staticmethod(ChangelogsClient.common_location_path) + parse_common_location_path = staticmethod( + ChangelogsClient.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: + ChangelogsAsyncClient: The constructed client. + """ + return ChangelogsClient.from_service_account_info.__func__(ChangelogsAsyncClient, 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: + ChangelogsAsyncClient: The constructed client. + """ + return ChangelogsClient.from_service_account_file.__func__(ChangelogsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ChangelogsTransport: + """Returns the transport used by the client instance. + + Returns: + ChangelogsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(ChangelogsClient).get_transport_class, type(ChangelogsClient) + ) + + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ChangelogsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the changelogs 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, ~.ChangelogsTransport]): 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 = ChangelogsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_changelogs( + self, + request: Union[changelog.ListChangelogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListChangelogsAsyncPager: + r"""Returns the list of Changelogs. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListChangelogsRequest, dict]): + The request object. The request message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3.Changelogs.ListChangelogs]. + parent (:class:`str`): + Required. The agent containing the changelogs. Format: + ``projects//locations//agents/``. + + 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_v3.services.changelogs.pagers.ListChangelogsAsyncPager: + The response message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3.Changelogs.ListChangelogs]. + + 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 = changelog.ListChangelogsRequest(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_changelogs, + 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.ListChangelogsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_changelog( + self, + request: Union[changelog.GetChangelogRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> changelog.Changelog: + r"""Retrieves the specified Changelog. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetChangelogRequest, dict]): + The request object. The request message for + [Changelogs.GetChangelog][google.cloud.dialogflow.cx.v3.Changelogs.GetChangelog]. + name (:class:`str`): + Required. The name of the changelog to get. Format: + ``projects//locations//agents//changelogs/``. + + 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_v3.types.Changelog: + Changelogs represents a change made + to a given agent. + + """ + # 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 = changelog.GetChangelogRequest(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_changelog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +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__ = ("ChangelogsAsyncClient",) diff --git a/google/cloud/dialogflowcx_v3/services/changelogs/client.py b/google/cloud/dialogflowcx_v3/services/changelogs/client.py new file mode 100644 index 00000000..1d77778f --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/changelogs/client.py @@ -0,0 +1,528 @@ +# -*- 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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.dialogflowcx_v3.services.changelogs import pagers +from google.cloud.dialogflowcx_v3.types import changelog +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ChangelogsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ChangelogsGrpcTransport +from .transports.grpc_asyncio import ChangelogsGrpcAsyncIOTransport + + +class ChangelogsClientMeta(type): + """Metaclass for the Changelogs 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[ChangelogsTransport]] + _transport_registry["grpc"] = ChangelogsGrpcTransport + _transport_registry["grpc_asyncio"] = ChangelogsGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ChangelogsTransport]: + """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 ChangelogsClient(metaclass=ChangelogsClientMeta): + """Service for managing + [Changelogs][google.cloud.dialogflow.cx.v3.Changelog]. + """ + + @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: + ChangelogsClient: 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: + ChangelogsClient: 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) -> ChangelogsTransport: + """Returns the transport used by the client instance. + + Returns: + ChangelogsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def changelog_path(project: str, location: str, agent: str, changelog: str,) -> str: + """Returns a fully-qualified changelog string.""" + return "projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}".format( + project=project, location=location, agent=agent, changelog=changelog, + ) + + @staticmethod + def parse_changelog_path(path: str) -> Dict[str, str]: + """Parses a changelog path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/changelogs/(?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, ChangelogsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the changelogs 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, ChangelogsTransport]): 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, ChangelogsTransport): + # transport is a ChangelogsTransport 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=True, + ) + + def list_changelogs( + self, + request: Union[changelog.ListChangelogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListChangelogsPager: + r"""Returns the list of Changelogs. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListChangelogsRequest, dict]): + The request object. The request message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3.Changelogs.ListChangelogs]. + parent (str): + Required. The agent containing the changelogs. Format: + ``projects//locations//agents/``. + + 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_v3.services.changelogs.pagers.ListChangelogsPager: + The response message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3.Changelogs.ListChangelogs]. + + 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 changelog.ListChangelogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, changelog.ListChangelogsRequest): + request = changelog.ListChangelogsRequest(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_changelogs] + + # 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.ListChangelogsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_changelog( + self, + request: Union[changelog.GetChangelogRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> changelog.Changelog: + r"""Retrieves the specified Changelog. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetChangelogRequest, dict]): + The request object. The request message for + [Changelogs.GetChangelog][google.cloud.dialogflow.cx.v3.Changelogs.GetChangelog]. + name (str): + Required. The name of the changelog to get. Format: + ``projects//locations//agents//changelogs/``. + + 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_v3.types.Changelog: + Changelogs represents a change made + to a given agent. + + """ + # 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 changelog.GetChangelogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, changelog.GetChangelogRequest): + request = changelog.GetChangelogRequest(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_changelog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +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__ = ("ChangelogsClient",) diff --git a/google/cloud/dialogflowcx_v3/services/changelogs/pagers.py b/google/cloud/dialogflowcx_v3/services/changelogs/pagers.py new file mode 100644 index 00000000..60583531 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/changelogs/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, + AsyncIterator, + Awaitable, + Callable, + Sequence, + Tuple, + Optional, + Iterator, +) + +from google.cloud.dialogflowcx_v3.types import changelog + + +class ListChangelogsPager: + """A pager for iterating through ``list_changelogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListChangelogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``changelogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListChangelogs`` requests and continue to iterate + through the ``changelogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListChangelogsResponse` + 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[..., changelog.ListChangelogsResponse], + request: changelog.ListChangelogsRequest, + response: changelog.ListChangelogsResponse, + *, + 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_v3.types.ListChangelogsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListChangelogsResponse): + 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 = changelog.ListChangelogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[changelog.ListChangelogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[changelog.Changelog]: + for page in self.pages: + yield from page.changelogs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListChangelogsAsyncPager: + """A pager for iterating through ``list_changelogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListChangelogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``changelogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListChangelogs`` requests and continue to iterate + through the ``changelogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListChangelogsResponse` + 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[changelog.ListChangelogsResponse]], + request: changelog.ListChangelogsRequest, + response: changelog.ListChangelogsResponse, + *, + 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_v3.types.ListChangelogsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListChangelogsResponse): + 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 = changelog.ListChangelogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[changelog.ListChangelogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[changelog.Changelog]: + async def async_generator(): + async for page in self.pages: + for response in page.changelogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflowcx_v3/services/changelogs/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/changelogs/transports/__init__.py new file mode 100644 index 00000000..882554f3 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/changelogs/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 ChangelogsTransport +from .grpc import ChangelogsGrpcTransport +from .grpc_asyncio import ChangelogsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ChangelogsTransport]] +_transport_registry["grpc"] = ChangelogsGrpcTransport +_transport_registry["grpc_asyncio"] = ChangelogsGrpcAsyncIOTransport + +__all__ = ( + "ChangelogsTransport", + "ChangelogsGrpcTransport", + "ChangelogsGrpcAsyncIOTransport", +) diff --git a/google/cloud/dialogflowcx_v3/services/changelogs/transports/base.py b/google/cloud/dialogflowcx_v3/services/changelogs/transports/base.py new file mode 100644 index 00000000..cf98123f --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/changelogs/transports/base.py @@ -0,0 +1,166 @@ +# -*- 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 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_v3.types import changelog + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ChangelogsTransport(abc.ABC): + """Abstract transport class for Changelogs.""" + + 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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_changelogs: gapic_v1.method.wrap_method( + self.list_changelogs, default_timeout=None, client_info=client_info, + ), + self.get_changelog: gapic_v1.method.wrap_method( + self.get_changelog, default_timeout=None, client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_changelogs( + self, + ) -> Callable[ + [changelog.ListChangelogsRequest], + Union[ + changelog.ListChangelogsResponse, + Awaitable[changelog.ListChangelogsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_changelog( + self, + ) -> Callable[ + [changelog.GetChangelogRequest], + Union[changelog.Changelog, Awaitable[changelog.Changelog]], + ]: + raise NotImplementedError() + + +__all__ = ("ChangelogsTransport",) diff --git a/google/cloud/dialogflowcx_v3/services/changelogs/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/changelogs/transports/grpc.py new file mode 100644 index 00000000..d10925ea --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/changelogs/transports/grpc.py @@ -0,0 +1,285 @@ +# -*- 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_v3.types import changelog +from .base import ChangelogsTransport, DEFAULT_CLIENT_INFO + + +class ChangelogsGrpcTransport(ChangelogsTransport): + """gRPC backend transport for Changelogs. + + Service for managing + [Changelogs][google.cloud.dialogflow.cx.v3.Changelog]. + + 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_changelogs( + self, + ) -> Callable[[changelog.ListChangelogsRequest], changelog.ListChangelogsResponse]: + r"""Return a callable for the list changelogs method over gRPC. + + Returns the list of Changelogs. + + Returns: + Callable[[~.ListChangelogsRequest], + ~.ListChangelogsResponse]: + 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_changelogs" not in self._stubs: + self._stubs["list_changelogs"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Changelogs/ListChangelogs", + request_serializer=changelog.ListChangelogsRequest.serialize, + response_deserializer=changelog.ListChangelogsResponse.deserialize, + ) + return self._stubs["list_changelogs"] + + @property + def get_changelog( + self, + ) -> Callable[[changelog.GetChangelogRequest], changelog.Changelog]: + r"""Return a callable for the get changelog method over gRPC. + + Retrieves the specified Changelog. + + Returns: + Callable[[~.GetChangelogRequest], + ~.Changelog]: + 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_changelog" not in self._stubs: + self._stubs["get_changelog"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Changelogs/GetChangelog", + request_serializer=changelog.GetChangelogRequest.serialize, + response_deserializer=changelog.Changelog.deserialize, + ) + return self._stubs["get_changelog"] + + def close(self): + self.grpc_channel.close() + + +__all__ = ("ChangelogsGrpcTransport",) diff --git a/google/cloud/dialogflowcx_v3/services/changelogs/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/changelogs/transports/grpc_asyncio.py new file mode 100644 index 00000000..f74f54d9 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/services/changelogs/transports/grpc_asyncio.py @@ -0,0 +1,289 @@ +# -*- 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 grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import changelog +from .base import ChangelogsTransport, DEFAULT_CLIENT_INFO +from .grpc import ChangelogsGrpcTransport + + +class ChangelogsGrpcAsyncIOTransport(ChangelogsTransport): + """gRPC AsyncIO backend transport for Changelogs. + + Service for managing + [Changelogs][google.cloud.dialogflow.cx.v3.Changelog]. + + 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_changelogs( + self, + ) -> Callable[ + [changelog.ListChangelogsRequest], Awaitable[changelog.ListChangelogsResponse] + ]: + r"""Return a callable for the list changelogs method over gRPC. + + Returns the list of Changelogs. + + Returns: + Callable[[~.ListChangelogsRequest], + Awaitable[~.ListChangelogsResponse]]: + 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_changelogs" not in self._stubs: + self._stubs["list_changelogs"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Changelogs/ListChangelogs", + request_serializer=changelog.ListChangelogsRequest.serialize, + response_deserializer=changelog.ListChangelogsResponse.deserialize, + ) + return self._stubs["list_changelogs"] + + @property + def get_changelog( + self, + ) -> Callable[[changelog.GetChangelogRequest], Awaitable[changelog.Changelog]]: + r"""Return a callable for the get changelog method over gRPC. + + Retrieves the specified Changelog. + + Returns: + Callable[[~.GetChangelogRequest], + Awaitable[~.Changelog]]: + 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_changelog" not in self._stubs: + self._stubs["get_changelog"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Changelogs/GetChangelog", + request_serializer=changelog.GetChangelogRequest.serialize, + response_deserializer=changelog.Changelog.deserialize, + ) + return self._stubs["get_changelog"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("ChangelogsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3/services/deployments/async_client.py b/google/cloud/dialogflowcx_v3/services/deployments/async_client.py index a72365ad..2503bea1 100644 --- a/google/cloud/dialogflowcx_v3/services/deployments/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/deployments/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.deployments import pagers from google.cloud.dialogflowcx_v3.types import deployment from google.protobuf import timestamp_pb2 # type: ignore @@ -170,10 +172,10 @@ def __init__( async def list_deployments( self, - request: deployment.ListDeploymentsRequest = None, + request: Union[deployment.ListDeploymentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListDeploymentsAsyncPager: @@ -181,7 +183,7 @@ async def list_deployments( [Environment][google.cloud.dialogflow.cx.v3.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListDeploymentsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListDeploymentsRequest, dict]): The request object. The request message for [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3.Deployments.ListDeployments]. parent (:class:`str`): @@ -253,10 +255,10 @@ async def list_deployments( async def get_deployment( self, - request: deployment.GetDeploymentRequest = None, + request: Union[deployment.GetDeploymentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> deployment.Deployment: @@ -264,7 +266,7 @@ async def get_deployment( [Deployment][google.cloud.dialogflow.cx.v3.Deployment]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetDeploymentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetDeploymentRequest, dict]): The request object. The request message for [Deployments.GetDeployment][google.cloud.dialogflow.cx.v3.Deployments.GetDeployment]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/deployments/client.py b/google/cloud/dialogflowcx_v3/services/deployments/client.py index 0eb48469..0ebea8b8 100644 --- a/google/cloud/dialogflowcx_v3/services/deployments/client.py +++ b/google/cloud/dialogflowcx_v3/services/deployments/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.deployments import pagers from google.cloud.dialogflowcx_v3.types import deployment from google.protobuf import timestamp_pb2 # type: ignore @@ -421,7 +423,7 @@ def list_deployments( request: Union[deployment.ListDeploymentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListDeploymentsPager: @@ -504,7 +506,7 @@ def get_deployment( request: Union[deployment.GetDeploymentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> deployment.Deployment: diff --git a/google/cloud/dialogflowcx_v3/services/deployments/transports/base.py b/google/cloud/dialogflowcx_v3/services/deployments/transports/base.py index ea44325f..8e8de46d 100644 --- a/google/cloud/dialogflowcx_v3/services/deployments/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/deployments/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -37,15 +36,6 @@ 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.""" @@ -98,7 +88,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -131,29 +121,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc_asyncio.py index b87f30b4..7fe407f5 100644 --- a/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py b/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py index 45b4399c..5e921640 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.entity_types import pagers from google.cloud.dialogflowcx_v3.types import entity_type from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type @@ -163,10 +165,10 @@ def __init__( async def list_entity_types( self, - request: entity_type.ListEntityTypesRequest = None, + request: Union[entity_type.ListEntityTypesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEntityTypesAsyncPager: @@ -174,7 +176,7 @@ async def list_entity_types( agent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListEntityTypesRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListEntityTypesRequest, dict]): The request object. The request message for [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. parent (:class:`str`): @@ -245,17 +247,17 @@ async def list_entity_types( async def get_entity_type( self, - request: entity_type.GetEntityTypeRequest = None, + request: Union[entity_type.GetEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> entity_type.EntityType: r"""Retrieves the specified entity type. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetEntityTypeRequest, dict]): The request object. The request message for [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.GetEntityType]. name (:class:`str`): @@ -348,11 +350,11 @@ async def get_entity_type( async def create_entity_type( self, - request: gcdc_entity_type.CreateEntityTypeRequest = None, + request: Union[gcdc_entity_type.CreateEntityTypeRequest, dict] = None, *, parent: str = None, entity_type: gcdc_entity_type.EntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_entity_type.EntityType: @@ -363,7 +365,7 @@ async def create_entity_type( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateEntityTypeRequest, dict]): The request object. The request message for [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.CreateEntityType]. parent (:class:`str`): @@ -463,11 +465,11 @@ async def create_entity_type( async def update_entity_type( self, - request: gcdc_entity_type.UpdateEntityTypeRequest = None, + request: Union[gcdc_entity_type.UpdateEntityTypeRequest, dict] = None, *, entity_type: gcdc_entity_type.EntityType = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_entity_type.EntityType: @@ -478,7 +480,7 @@ async def update_entity_type( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateEntityTypeRequest, dict]): The request object. The request message for [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. entity_type (:class:`google.cloud.dialogflowcx_v3.types.EntityType`): @@ -580,10 +582,10 @@ async def update_entity_type( async def delete_entity_type( self, - request: entity_type.DeleteEntityTypeRequest = None, + request: Union[entity_type.DeleteEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -594,7 +596,7 @@ async def delete_entity_type( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteEntityTypeRequest, dict]): The request object. The request message for [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.DeleteEntityType]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/entity_types/client.py b/google/cloud/dialogflowcx_v3/services/entity_types/client.py index 843d73f7..5be392d4 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/client.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.entity_types import pagers from google.cloud.dialogflowcx_v3.types import entity_type from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type @@ -356,7 +358,7 @@ def list_entity_types( request: Union[entity_type.ListEntityTypesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEntityTypesPager: @@ -438,7 +440,7 @@ def get_entity_type( request: Union[entity_type.GetEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> entity_type.EntityType: @@ -542,7 +544,7 @@ def create_entity_type( *, parent: str = None, entity_type: gcdc_entity_type.EntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_entity_type.EntityType: @@ -657,7 +659,7 @@ def update_entity_type( *, entity_type: gcdc_entity_type.EntityType = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_entity_type.EntityType: @@ -773,7 +775,7 @@ def delete_entity_type( request: Union[entity_type.DeleteEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py b/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py index 31590449..731013e6 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -39,15 +38,6 @@ 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 EntityTypesTransport(abc.ABC): """Abstract transport class for EntityTypes.""" @@ -100,7 +90,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -133,29 +123,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py index a36f040d..ab87cf53 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3/services/environments/async_client.py b/google/cloud/dialogflowcx_v3/services/environments/async_client.py index 130d1046..0c207ded 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/environments/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3.services.environments import pagers @@ -181,10 +183,10 @@ def __init__( async def list_environments( self, - request: environment.ListEnvironmentsRequest = None, + request: Union[environment.ListEnvironmentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEnvironmentsAsyncPager: @@ -192,7 +194,7 @@ async def list_environments( [Agent][google.cloud.dialogflow.cx.v3.Agent]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListEnvironmentsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListEnvironmentsRequest, dict]): The request object. The request message for [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. parent (:class:`str`): @@ -264,10 +266,10 @@ async def list_environments( async def get_environment( self, - request: environment.GetEnvironmentRequest = None, + request: Union[environment.GetEnvironmentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> environment.Environment: @@ -275,7 +277,7 @@ async def get_environment( [Environment][google.cloud.dialogflow.cx.v3.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetEnvironmentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetEnvironmentRequest, dict]): The request object. The request message for [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3.Environments.GetEnvironment]. name (:class:`str`): @@ -351,11 +353,11 @@ async def get_environment( async def create_environment( self, - request: gcdc_environment.CreateEnvironmentRequest = None, + request: Union[gcdc_environment.CreateEnvironmentRequest, dict] = None, *, parent: str = None, environment: gcdc_environment.Environment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -374,7 +376,7 @@ async def create_environment( [Environment][google.cloud.dialogflow.cx.v3.Environment] Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateEnvironmentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateEnvironmentRequest, dict]): The request object. The request message for [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3.Environments.CreateEnvironment]. parent (:class:`str`): @@ -465,11 +467,11 @@ async def create_environment( async def update_environment( self, - request: gcdc_environment.UpdateEnvironmentRequest = None, + request: Union[gcdc_environment.UpdateEnvironmentRequest, dict] = None, *, environment: gcdc_environment.Environment = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -487,7 +489,7 @@ async def update_environment( [Environment][google.cloud.dialogflow.cx.v3.Environment] Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateEnvironmentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateEnvironmentRequest, dict]): The request object. The request message for [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3.Environments.UpdateEnvironment]. environment (:class:`google.cloud.dialogflowcx_v3.types.Environment`): @@ -576,10 +578,10 @@ async def update_environment( async def delete_environment( self, - request: environment.DeleteEnvironmentRequest = None, + request: Union[environment.DeleteEnvironmentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -587,7 +589,7 @@ async def delete_environment( [Environment][google.cloud.dialogflow.cx.v3.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteEnvironmentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteEnvironmentRequest, dict]): The request object. The request message for [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3.Environments.DeleteEnvironment]. name (:class:`str`): @@ -643,10 +645,10 @@ async def delete_environment( async def lookup_environment_history( self, - request: environment.LookupEnvironmentHistoryRequest = None, + request: Union[environment.LookupEnvironmentHistoryRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.LookupEnvironmentHistoryAsyncPager: @@ -654,7 +656,7 @@ async def lookup_environment_history( [Environment][google.cloud.dialogflow.cx.v3.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest, dict]): The request object. The request message for [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. name (:class:`str`): @@ -725,9 +727,9 @@ async def lookup_environment_history( async def run_continuous_test( self, - request: environment.RunContinuousTestRequest = None, + request: Union[environment.RunContinuousTestRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -745,7 +747,7 @@ async def run_continuous_test( [RunContinuousTestResponse][google.cloud.dialogflow.cx.v3.RunContinuousTestResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3.types.RunContinuousTestRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.RunContinuousTestRequest, dict]): The request object. The request message for [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3.Environments.RunContinuousTest]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -799,10 +801,10 @@ async def run_continuous_test( async def list_continuous_test_results( self, - request: environment.ListContinuousTestResultsRequest = None, + request: Union[environment.ListContinuousTestResultsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListContinuousTestResultsAsyncPager: @@ -810,7 +812,7 @@ async def list_continuous_test_results( environment. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsRequest, dict]): The request object. The request message for [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3.Environments.ListContinuousTestResults]. parent (:class:`str`): @@ -880,9 +882,9 @@ async def list_continuous_test_results( async def deploy_flow( self, - request: environment.DeployFlowRequest = None, + request: Union[environment.DeployFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -900,7 +902,7 @@ async def deploy_flow( [DeployFlowResponse][google.cloud.dialogflow.cx.v3.DeployFlowResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeployFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeployFlowRequest, dict]): The request object. The request message for [Environments.DeployFlow][google.cloud.dialogflow.cx.v3.Environments.DeployFlow]. retry (google.api_core.retry.Retry): Designation of what errors, if any, diff --git a/google/cloud/dialogflowcx_v3/services/environments/client.py b/google/cloud/dialogflowcx_v3/services/environments/client.py index c39043d9..f804f252 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/client.py +++ b/google/cloud/dialogflowcx_v3/services/environments/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3.services.environments import pagers @@ -442,7 +444,7 @@ def list_environments( request: Union[environment.ListEnvironmentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEnvironmentsPager: @@ -525,7 +527,7 @@ def get_environment( request: Union[environment.GetEnvironmentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> environment.Environment: @@ -613,7 +615,7 @@ def create_environment( *, parent: str = None, environment: gcdc_environment.Environment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -727,7 +729,7 @@ def update_environment( *, environment: gcdc_environment.Environment = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -837,7 +839,7 @@ def delete_environment( request: Union[environment.DeleteEnvironmentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -904,7 +906,7 @@ def lookup_environment_history( request: Union[environment.LookupEnvironmentHistoryRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.LookupEnvironmentHistoryPager: @@ -987,7 +989,7 @@ def run_continuous_test( self, request: Union[environment.RunContinuousTestRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1063,7 +1065,7 @@ def list_continuous_test_results( request: Union[environment.ListContinuousTestResultsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListContinuousTestResultsPager: @@ -1145,7 +1147,7 @@ def deploy_flow( self, request: Union[environment.DeployFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: diff --git a/google/cloud/dialogflowcx_v3/services/environments/transports/base.py b/google/cloud/dialogflowcx_v3/services/environments/transports/base.py index 27b4aa98..fe79de32 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/environments/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 EnvironmentsTransport(abc.ABC): """Abstract transport class for Environments.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { @@ -204,7 +171,7 @@ def close(self): raise NotImplementedError() @property - def operations_client(self) -> operations_v1.OperationsClient: + def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py index 3bc91521..44c7e8f8 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py @@ -115,7 +115,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py index be3cc4ce..eaf1a881 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py @@ -21,7 +21,6 @@ from google.api_core import operations_v1 # 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 @@ -162,7 +161,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3/services/experiments/async_client.py b/google/cloud/dialogflowcx_v3/services/experiments/async_client.py index 55c90bc2..cfbb2ed6 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.experiments import pagers from google.cloud.dialogflowcx_v3.types import experiment from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment @@ -167,10 +169,10 @@ def __init__( async def list_experiments( self, - request: experiment.ListExperimentsRequest = None, + request: Union[experiment.ListExperimentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListExperimentsAsyncPager: @@ -178,7 +180,7 @@ async def list_experiments( [Environment][google.cloud.dialogflow.cx.v3.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListExperimentsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListExperimentsRequest, dict]): The request object. The request message for [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. parent (:class:`str`): @@ -250,10 +252,10 @@ async def list_experiments( async def get_experiment( self, - request: experiment.GetExperimentRequest = None, + request: Union[experiment.GetExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: @@ -261,7 +263,7 @@ async def get_experiment( [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetExperimentRequest, dict]): The request object. The request message for [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. name (:class:`str`): @@ -324,11 +326,11 @@ async def get_experiment( async def create_experiment( self, - request: gcdc_experiment.CreateExperimentRequest = None, + request: Union[gcdc_experiment.CreateExperimentRequest, dict] = None, *, parent: str = None, experiment: gcdc_experiment.Experiment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_experiment.Experiment: @@ -338,7 +340,7 @@ async def create_experiment( [Environment][google.cloud.dialogflow.cx.v3.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateExperimentRequest, dict]): The request object. The request message for [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. parent (:class:`str`): @@ -410,11 +412,11 @@ async def create_experiment( async def update_experiment( self, - request: gcdc_experiment.UpdateExperimentRequest = None, + request: Union[gcdc_experiment.UpdateExperimentRequest, dict] = None, *, experiment: gcdc_experiment.Experiment = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_experiment.Experiment: @@ -422,7 +424,7 @@ async def update_experiment( [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest, dict]): The request object. The request message for [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. experiment (:class:`google.cloud.dialogflowcx_v3.types.Experiment`): @@ -492,10 +494,10 @@ async def update_experiment( async def delete_experiment( self, - request: experiment.DeleteExperimentRequest = None, + request: Union[experiment.DeleteExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -503,7 +505,7 @@ async def delete_experiment( [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest, dict]): The request object. The request message for [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. name (:class:`str`): @@ -559,10 +561,10 @@ async def delete_experiment( async def start_experiment( self, - request: experiment.StartExperimentRequest = None, + request: Union[experiment.StartExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: @@ -571,7 +573,7 @@ async def start_experiment( only changes the state of experiment from PENDING to RUNNING. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.StartExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.StartExperimentRequest, dict]): The request object. The request message for [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. name (:class:`str`): @@ -633,10 +635,10 @@ async def start_experiment( async def stop_experiment( self, - request: experiment.StopExperimentRequest = None, + request: Union[experiment.StopExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: @@ -645,7 +647,7 @@ async def stop_experiment( only changes the state of experiment from RUNNING to DONE. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.StopExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.StopExperimentRequest, dict]): The request object. The request message for [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/experiments/client.py b/google/cloud/dialogflowcx_v3/services/experiments/client.py index 165563de..bc5e60b5 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/client.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.experiments import pagers from google.cloud.dialogflowcx_v3.types import experiment from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment @@ -380,7 +382,7 @@ def list_experiments( request: Union[experiment.ListExperimentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListExperimentsPager: @@ -463,7 +465,7 @@ def get_experiment( request: Union[experiment.GetExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: @@ -538,7 +540,7 @@ def create_experiment( *, parent: str = None, experiment: gcdc_experiment.Experiment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_experiment.Experiment: @@ -624,7 +626,7 @@ def update_experiment( *, experiment: gcdc_experiment.Experiment = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_experiment.Experiment: @@ -705,7 +707,7 @@ def delete_experiment( request: Union[experiment.DeleteExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -772,7 +774,7 @@ def start_experiment( request: Union[experiment.StartExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: @@ -846,7 +848,7 @@ def stop_experiment( request: Union[experiment.StopExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: diff --git a/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py b/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py index 2225f4a0..eeaecb0f 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -39,15 +38,6 @@ 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 ExperimentsTransport(abc.ABC): """Abstract transport class for Experiments.""" @@ -100,7 +90,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -133,29 +123,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py index d5930cc0..11817088 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3/services/flows/async_client.py b/google/cloud/dialogflowcx_v3/services/flows/async_client.py index 9b8c96cc..3befadc5 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/flows/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3.services.flows import pagers @@ -176,11 +178,11 @@ def __init__( async def create_flow( self, - request: gcdc_flow.CreateFlowRequest = None, + request: Union[gcdc_flow.CreateFlowRequest, dict] = None, *, parent: str = None, flow: gcdc_flow.Flow = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_flow.Flow: @@ -191,7 +193,7 @@ async def create_flow( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateFlowRequest, dict]): The request object. The request message for [Flows.CreateFlow][google.cloud.dialogflow.cx.v3.Flows.CreateFlow]. parent (:class:`str`): @@ -280,17 +282,17 @@ async def create_flow( async def delete_flow( self, - request: flow.DeleteFlowRequest = None, + request: Union[flow.DeleteFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes a specified flow. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteFlowRequest, dict]): The request object. The request message for [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3.Flows.DeleteFlow]. name (:class:`str`): @@ -344,17 +346,17 @@ async def delete_flow( async def list_flows( self, - request: flow.ListFlowsRequest = None, + request: Union[flow.ListFlowsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListFlowsAsyncPager: r"""Returns the list of all flows in the specified agent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListFlowsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListFlowsRequest, dict]): The request object. The request message for [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. parent (:class:`str`): @@ -424,17 +426,17 @@ async def list_flows( async def get_flow( self, - request: flow.GetFlowRequest = None, + request: Union[flow.GetFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.Flow: r"""Retrieves the specified flow. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetFlowRequest, dict]): The request object. The response message for [Flows.GetFlow][google.cloud.dialogflow.cx.v3.Flows.GetFlow]. name (:class:`str`): @@ -516,11 +518,11 @@ async def get_flow( async def update_flow( self, - request: gcdc_flow.UpdateFlowRequest = None, + request: Union[gcdc_flow.UpdateFlowRequest, dict] = None, *, flow: gcdc_flow.Flow = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_flow.Flow: @@ -531,7 +533,7 @@ async def update_flow( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateFlowRequest, dict]): The request object. The request message for [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3.Flows.UpdateFlow]. flow (:class:`google.cloud.dialogflowcx_v3.types.Flow`): @@ -623,10 +625,10 @@ async def update_flow( async def train_flow( self, - request: flow.TrainFlowRequest = None, + request: Union[flow.TrainFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -648,7 +650,7 @@ async def train_flow( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.TrainFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.TrainFlowRequest, dict]): The request object. The request message for [Flows.TrainFlow][google.cloud.dialogflow.cx.v3.Flows.TrainFlow]. name (:class:`str`): @@ -730,9 +732,9 @@ async def train_flow( async def validate_flow( self, - request: flow.ValidateFlowRequest = None, + request: Union[flow.ValidateFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.FlowValidationResult: @@ -742,7 +744,7 @@ async def validate_flow( results. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ValidateFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ValidateFlowRequest, dict]): The request object. The request message for [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3.Flows.ValidateFlow]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -782,10 +784,10 @@ async def validate_flow( async def get_flow_validation_result( self, - request: flow.GetFlowValidationResultRequest = None, + request: Union[flow.GetFlowValidationResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.FlowValidationResult: @@ -793,7 +795,7 @@ async def get_flow_validation_result( validation is performed when ValidateFlow is called. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest, dict]): The request object. The request message for [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. name (:class:`str`): @@ -854,9 +856,9 @@ async def get_flow_validation_result( async def import_flow( self, - request: flow.ImportFlowRequest = None, + request: Union[flow.ImportFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -878,7 +880,7 @@ async def import_flow( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ImportFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ImportFlowRequest, dict]): The request object. The request message for [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -930,9 +932,9 @@ async def import_flow( async def export_flow( self, - request: flow.ExportFlowRequest = None, + request: Union[flow.ExportFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -952,7 +954,7 @@ async def export_flow( flow references will also be exported. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ExportFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ExportFlowRequest, dict]): The request object. The request message for [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. retry (google.api_core.retry.Retry): Designation of what errors, if any, diff --git a/google/cloud/dialogflowcx_v3/services/flows/client.py b/google/cloud/dialogflowcx_v3/services/flows/client.py index a8d54a03..a157780c 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/client.py +++ b/google/cloud/dialogflowcx_v3/services/flows/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3.services.flows import pagers @@ -450,7 +452,7 @@ def create_flow( *, parent: str = None, flow: gcdc_flow.Flow = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_flow.Flow: @@ -553,7 +555,7 @@ def delete_flow( request: Union[flow.DeleteFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -617,7 +619,7 @@ def list_flows( request: Union[flow.ListFlowsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListFlowsPager: @@ -697,7 +699,7 @@ def get_flow( request: Union[flow.GetFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.Flow: @@ -790,7 +792,7 @@ def update_flow( *, flow: gcdc_flow.Flow = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_flow.Flow: @@ -896,7 +898,7 @@ def train_flow( request: Union[flow.TrainFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1002,7 +1004,7 @@ def validate_flow( self, request: Union[flow.ValidateFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.FlowValidationResult: @@ -1056,7 +1058,7 @@ def get_flow_validation_result( request: Union[flow.GetFlowValidationResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.FlowValidationResult: @@ -1129,7 +1131,7 @@ def import_flow( self, request: Union[flow.ImportFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1206,7 +1208,7 @@ def export_flow( self, request: Union[flow.ExportFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: diff --git a/google/cloud/dialogflowcx_v3/services/flows/transports/base.py b/google/cloud/dialogflowcx_v3/services/flows/transports/base.py index d2fac5dd..6705d227 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/flows/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 FlowsTransport(abc.ABC): """Abstract transport class for Flows.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { @@ -205,7 +172,7 @@ def close(self): raise NotImplementedError() @property - def operations_client(self) -> operations_v1.OperationsClient: + def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py index 3fa7afd7..f7525571 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py @@ -114,7 +114,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py index 5cc7de70..2bdc752c 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py @@ -21,7 +21,6 @@ from google.api_core import operations_v1 # 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 @@ -161,7 +160,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3/services/intents/async_client.py b/google/cloud/dialogflowcx_v3/services/intents/async_client.py index d835a08a..23a807cd 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/intents/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.intents import pagers from google.cloud.dialogflowcx_v3.types import intent from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent @@ -161,10 +163,10 @@ def __init__( async def list_intents( self, - request: intent.ListIntentsRequest = None, + request: Union[intent.ListIntentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListIntentsAsyncPager: @@ -172,7 +174,7 @@ async def list_intents( agent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListIntentsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListIntentsRequest, dict]): The request object. The request message for [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. parent (:class:`str`): @@ -242,17 +244,17 @@ async def list_intents( async def get_intent( self, - request: intent.GetIntentRequest = None, + request: Union[intent.GetIntentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> intent.Intent: r"""Retrieves the specified intent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetIntentRequest, dict]): The request object. The request message for [Intents.GetIntent][google.cloud.dialogflow.cx.v3.Intents.GetIntent]. name (:class:`str`): @@ -318,11 +320,11 @@ async def get_intent( async def create_intent( self, - request: gcdc_intent.CreateIntentRequest = None, + request: Union[gcdc_intent.CreateIntentRequest, dict] = None, *, parent: str = None, intent: gcdc_intent.Intent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_intent.Intent: @@ -333,7 +335,7 @@ async def create_intent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateIntentRequest, dict]): The request object. The request message for [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent]. parent (:class:`str`): @@ -406,11 +408,11 @@ async def create_intent( async def update_intent( self, - request: gcdc_intent.UpdateIntentRequest = None, + request: Union[gcdc_intent.UpdateIntentRequest, dict] = None, *, intent: gcdc_intent.Intent = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_intent.Intent: @@ -421,7 +423,7 @@ async def update_intent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateIntentRequest, dict]): The request object. The request message for [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent]. intent (:class:`google.cloud.dialogflowcx_v3.types.Intent`): @@ -497,10 +499,10 @@ async def update_intent( async def delete_intent( self, - request: intent.DeleteIntentRequest = None, + request: Union[intent.DeleteIntentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -511,7 +513,7 @@ async def delete_intent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteIntentRequest, dict]): The request object. The request message for [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3.Intents.DeleteIntent]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/intents/client.py b/google/cloud/dialogflowcx_v3/services/intents/client.py index 5b0b1b13..fabae548 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/client.py +++ b/google/cloud/dialogflowcx_v3/services/intents/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.intents import pagers from google.cloud.dialogflowcx_v3.types import intent from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent @@ -372,7 +374,7 @@ def list_intents( request: Union[intent.ListIntentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListIntentsPager: @@ -453,7 +455,7 @@ def get_intent( request: Union[intent.GetIntentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> intent.Intent: @@ -530,7 +532,7 @@ def create_intent( *, parent: str = None, intent: gcdc_intent.Intent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_intent.Intent: @@ -618,7 +620,7 @@ def update_intent( *, intent: gcdc_intent.Intent = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_intent.Intent: @@ -708,7 +710,7 @@ def delete_intent( request: Union[intent.DeleteIntentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3/services/intents/transports/base.py b/google/cloud/dialogflowcx_v3/services/intents/transports/base.py index 28755478..6bed6335 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/intents/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -39,15 +38,6 @@ 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 IntentsTransport(abc.ABC): """Abstract transport class for Intents.""" @@ -100,7 +90,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -133,29 +123,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py index f40cd07c..9a0b505f 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3/services/pages/async_client.py b/google/cloud/dialogflowcx_v3/services/pages/async_client.py index 03c5ddeb..43eb3147 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/pages/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.pages import pagers from google.cloud.dialogflowcx_v3.types import fulfillment from google.cloud.dialogflowcx_v3.types import page @@ -168,17 +170,17 @@ def __init__( async def list_pages( self, - request: page.ListPagesRequest = None, + request: Union[page.ListPagesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListPagesAsyncPager: r"""Returns the list of all pages in the specified flow. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListPagesRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListPagesRequest, dict]): The request object. The request message for [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. parent (:class:`str`): @@ -248,17 +250,17 @@ async def list_pages( async def get_page( self, - request: page.GetPageRequest = None, + request: Union[page.GetPageRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> page.Page: r"""Retrieves the specified page. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetPageRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetPageRequest, dict]): The request object. The request message for [Pages.GetPage][google.cloud.dialogflow.cx.v3.Pages.GetPage]. name (:class:`str`): @@ -339,11 +341,11 @@ async def get_page( async def create_page( self, - request: gcdc_page.CreatePageRequest = None, + request: Union[gcdc_page.CreatePageRequest, dict] = None, *, parent: str = None, page: gcdc_page.Page = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_page.Page: @@ -354,7 +356,7 @@ async def create_page( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreatePageRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreatePageRequest, dict]): The request object. The request message for [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage]. parent (:class:`str`): @@ -442,11 +444,11 @@ async def create_page( async def update_page( self, - request: gcdc_page.UpdatePageRequest = None, + request: Union[gcdc_page.UpdatePageRequest, dict] = None, *, page: gcdc_page.Page = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_page.Page: @@ -457,7 +459,7 @@ async def update_page( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdatePageRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdatePageRequest, dict]): The request object. The request message for [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage]. page (:class:`google.cloud.dialogflowcx_v3.types.Page`): @@ -548,10 +550,10 @@ async def update_page( async def delete_page( self, - request: page.DeletePageRequest = None, + request: Union[page.DeletePageRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -562,7 +564,7 @@ async def delete_page( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeletePageRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeletePageRequest, dict]): The request object. The request message for [Pages.DeletePage][google.cloud.dialogflow.cx.v3.Pages.DeletePage]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/pages/client.py b/google/cloud/dialogflowcx_v3/services/pages/client.py index 6e73a5d3..0f145723 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/client.py +++ b/google/cloud/dialogflowcx_v3/services/pages/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.pages import pagers from google.cloud.dialogflowcx_v3.types import fulfillment from google.cloud.dialogflowcx_v3.types import page @@ -443,7 +445,7 @@ def list_pages( request: Union[page.ListPagesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListPagesPager: @@ -523,7 +525,7 @@ def get_page( request: Union[page.GetPageRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> page.Page: @@ -615,7 +617,7 @@ def create_page( *, parent: str = None, page: gcdc_page.Page = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_page.Page: @@ -718,7 +720,7 @@ def update_page( *, page: gcdc_page.Page = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_page.Page: @@ -823,7 +825,7 @@ def delete_page( request: Union[page.DeletePageRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3/services/pages/transports/base.py b/google/cloud/dialogflowcx_v3/services/pages/transports/base.py index b812b060..64c89614 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/pages/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -39,15 +38,6 @@ 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 PagesTransport(abc.ABC): """Abstract transport class for Pages.""" @@ -100,7 +90,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -133,29 +123,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py index ca446dbe..9de0030e 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py b/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py index e9011cbf..ac83946d 100644 --- a/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.security_settings_service import pagers from google.cloud.dialogflowcx_v3.types import security_settings from google.cloud.dialogflowcx_v3.types import ( @@ -188,18 +190,20 @@ def __init__( async def create_security_settings( self, - request: gcdc_security_settings.CreateSecuritySettingsRequest = None, + request: Union[ + gcdc_security_settings.CreateSecuritySettingsRequest, dict + ] = None, *, parent: str = None, security_settings: gcdc_security_settings.SecuritySettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_security_settings.SecuritySettings: r"""Create security settings in the specified location. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest, dict]): The request object. The request message for [SecuritySettings.CreateSecuritySettings][]. parent (:class:`str`): @@ -275,10 +279,10 @@ async def create_security_settings( async def get_security_settings( self, - request: security_settings.GetSecuritySettingsRequest = None, + request: Union[security_settings.GetSecuritySettingsRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> security_settings.SecuritySettings: @@ -287,7 +291,7 @@ async def get_security_settings( The returned settings may be stale by up to 1 minute. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest, dict]): The request object. The request message for [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings]. name (:class:`str`): @@ -352,11 +356,13 @@ async def get_security_settings( async def update_security_settings( self, - request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, + request: Union[ + gcdc_security_settings.UpdateSecuritySettingsRequest, dict + ] = None, *, security_settings: gcdc_security_settings.SecuritySettings = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_security_settings.SecuritySettings: @@ -364,7 +370,7 @@ async def update_security_settings( [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest, dict]): The request object. The request message for [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. security_settings (:class:`google.cloud.dialogflowcx_v3.types.SecuritySettings`): @@ -441,10 +447,10 @@ async def update_security_settings( async def list_security_settings( self, - request: security_settings.ListSecuritySettingsRequest = None, + request: Union[security_settings.ListSecuritySettingsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSecuritySettingsAsyncPager: @@ -452,7 +458,7 @@ async def list_security_settings( specified location. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest, dict]): The request object. The request message for [SecuritySettings.ListSecuritySettings][]. parent (:class:`str`): @@ -523,10 +529,10 @@ async def list_security_settings( async def delete_security_settings( self, - request: security_settings.DeleteSecuritySettingsRequest = None, + request: Union[security_settings.DeleteSecuritySettingsRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -534,7 +540,7 @@ async def delete_security_settings( [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest, dict]): The request object. The request message for [SecuritySettings.DeleteSecuritySettings][]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py b/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py index 70360c7d..83a24a83 100644 --- a/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py +++ b/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.security_settings_service import pagers from google.cloud.dialogflowcx_v3.types import security_settings from google.cloud.dialogflowcx_v3.types import ( @@ -403,7 +405,7 @@ def create_security_settings( *, parent: str = None, security_settings: gcdc_security_settings.SecuritySettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_security_settings.SecuritySettings: @@ -491,7 +493,7 @@ def get_security_settings( request: Union[security_settings.GetSecuritySettingsRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> security_settings.SecuritySettings: @@ -571,7 +573,7 @@ def update_security_settings( *, security_settings: gcdc_security_settings.SecuritySettings = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_security_settings.SecuritySettings: @@ -661,7 +663,7 @@ def list_security_settings( request: Union[security_settings.ListSecuritySettingsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSecuritySettingsPager: @@ -743,7 +745,7 @@ def delete_security_settings( request: Union[security_settings.DeleteSecuritySettingsRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py b/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py index 99f05152..4a7b8e93 100644 --- a/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 SecuritySettingsServiceTransport(abc.ABC): """Abstract transport class for SecuritySettingsService.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py index 1e3660cc..9641b545 100644 --- a/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py b/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py index 4530fa5d..b031bb6d 100644 --- a/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.session_entity_types import pagers from google.cloud.dialogflowcx_v3.types import entity_type from google.cloud.dialogflowcx_v3.types import session_entity_type @@ -175,10 +177,10 @@ def __init__( async def list_session_entity_types( self, - request: session_entity_type.ListSessionEntityTypesRequest = None, + request: Union[session_entity_type.ListSessionEntityTypesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSessionEntityTypesAsyncPager: @@ -186,7 +188,7 @@ async def list_session_entity_types( specified session. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest, dict]): The request object. The request message for [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. parent (:class:`str`): @@ -261,17 +263,17 @@ async def list_session_entity_types( async def get_session_entity_type( self, - request: session_entity_type.GetSessionEntityTypeRequest = None, + request: Union[session_entity_type.GetSessionEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session_entity_type.SessionEntityType: r"""Retrieves the specified session entity type. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest, dict]): The request object. The request message for [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType]. name (:class:`str`): @@ -350,18 +352,20 @@ async def get_session_entity_type( async def create_session_entity_type( self, - request: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, + request: Union[ + gcdc_session_entity_type.CreateSessionEntityTypeRequest, dict + ] = None, *, parent: str = None, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: r"""Creates a session entity type. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest, dict]): The request object. The request message for [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType]. parent (:class:`str`): @@ -450,18 +454,20 @@ async def create_session_entity_type( async def update_session_entity_type( self, - request: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, + request: Union[ + gcdc_session_entity_type.UpdateSessionEntityTypeRequest, dict + ] = None, *, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: r"""Updates the specified session entity type. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest, dict]): The request object. The request message for [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType]. session_entity_type (:class:`google.cloud.dialogflowcx_v3.types.SessionEntityType`): @@ -551,17 +557,17 @@ async def update_session_entity_type( async def delete_session_entity_type( self, - request: session_entity_type.DeleteSessionEntityTypeRequest = None, + request: Union[session_entity_type.DeleteSessionEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified session entity type. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest, dict]): The request object. The request message for [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py b/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py index 444d4b4f..623e2a75 100644 --- a/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py +++ b/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.session_entity_types import pagers from google.cloud.dialogflowcx_v3.types import entity_type from google.cloud.dialogflowcx_v3.types import session_entity_type @@ -367,7 +369,7 @@ def list_session_entity_types( request: Union[session_entity_type.ListSessionEntityTypesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSessionEntityTypesPager: @@ -455,7 +457,7 @@ def get_session_entity_type( request: Union[session_entity_type.GetSessionEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session_entity_type.SessionEntityType: @@ -547,7 +549,7 @@ def create_session_entity_type( *, parent: str = None, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: @@ -653,7 +655,7 @@ def update_session_entity_type( *, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: @@ -757,7 +759,7 @@ def delete_session_entity_type( request: Union[session_entity_type.DeleteSessionEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py b/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py index bc3aebba..2dfe7364 100644 --- a/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 SessionEntityTypesTransport(abc.ABC): """Abstract transport class for SessionEntityTypes.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py index 268f2343..00a82c80 100644 --- a/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3/services/sessions/async_client.py b/google/cloud/dialogflowcx_v3/services/sessions/async_client.py index 3522924b..eafec731 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/async_client.py @@ -28,13 +28,15 @@ ) import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.types import audio_config from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import session @@ -191,9 +193,9 @@ def __init__( async def detect_intent( self, - request: session.DetectIntentRequest = None, + request: Union[session.DetectIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.DetectIntentResponse: @@ -207,7 +209,7 @@ async def detect_intent( environments `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DetectIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DetectIntentRequest, dict]): The request object. The request to detect user's intent. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -257,7 +259,7 @@ def streaming_detect_intent( self, requests: AsyncIterator[session.StreamingDetectIntentRequest] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> Awaitable[AsyncIterable[session.StreamingDetectIntentResponse]]: @@ -315,23 +317,37 @@ def streaming_detect_intent( Returns: AsyncIterable[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentResponse]: The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. If enable_partial_response is true, the following - N messages (currently 1 <= N <= 4) contain - detect_intent_response. The first (N-1) - detect_intent_responses will have response_type - set to PARTIAL. The last detect_intent_response - has response_type set to FINAL. If response_type - is false, response stream only contains the final - detect_intent_response. + [StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] + method. + + Multiple response messages (N) can be returned in + order. + + The first (N-1) responses set either the + recognition_result or detect_intent_response field, + depending on the request: + + - If the + StreamingDetectIntentRequest.query_input.audio + field was set, and the + StreamingDetectIntentRequest.enable_partial_response + field was false, the recognition_result field is + populated for each of the (N-1) responses. See the + [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3.StreamingRecognitionResult] + message for details about the result message + sequence. + - If the + StreamingDetectIntentRequest.enable_partial_response + field was true, the detect_intent_response field + is populated for each of the (N-1) responses, + where 1 <= N <= 4. These responses set the + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3.DetectIntentResponse.response_type] + field to PARTIAL. + + For the final Nth response message, the + detect_intent_response is fully populated, and + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3.DetectIntentResponse.response_type] + is set to FINAL. """ @@ -351,9 +367,9 @@ def streaming_detect_intent( async def match_intent( self, - request: session.MatchIntentRequest = None, + request: Union[session.MatchIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.MatchIntentResponse: @@ -361,7 +377,7 @@ async def match_intent( change the session status. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.MatchIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.MatchIntentRequest, dict]): The request object. Request of [MatchIntent][]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -398,9 +414,9 @@ async def match_intent( async def fulfill_intent( self, - request: session.FulfillIntentRequest = None, + request: Union[session.FulfillIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.FulfillIntentResponse: @@ -413,7 +429,7 @@ async def fulfill_intent( Otherwise, the behavior is undefined. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.FulfillIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.FulfillIntentRequest, dict]): The request object. Request of [FulfillIntent][] retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/cloud/dialogflowcx_v3/services/sessions/client.py b/google/cloud/dialogflowcx_v3/services/sessions/client.py index fff5a339..3d10637c 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/client.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.types import audio_config from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import session @@ -500,7 +502,7 @@ def detect_intent( self, request: Union[session.DetectIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.DetectIntentResponse: @@ -556,7 +558,7 @@ def streaming_detect_intent( self, requests: Iterator[session.StreamingDetectIntentRequest] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> Iterable[session.StreamingDetectIntentResponse]: @@ -614,23 +616,37 @@ def streaming_detect_intent( Returns: Iterable[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentResponse]: The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. If enable_partial_response is true, the following - N messages (currently 1 <= N <= 4) contain - detect_intent_response. The first (N-1) - detect_intent_responses will have response_type - set to PARTIAL. The last detect_intent_response - has response_type set to FINAL. If response_type - is false, response stream only contains the final - detect_intent_response. + [StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] + method. + + Multiple response messages (N) can be returned in + order. + + The first (N-1) responses set either the + recognition_result or detect_intent_response field, + depending on the request: + + - If the + StreamingDetectIntentRequest.query_input.audio + field was set, and the + StreamingDetectIntentRequest.enable_partial_response + field was false, the recognition_result field is + populated for each of the (N-1) responses. See the + [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3.StreamingRecognitionResult] + message for details about the result message + sequence. + - If the + StreamingDetectIntentRequest.enable_partial_response + field was true, the detect_intent_response field + is populated for each of the (N-1) responses, + where 1 <= N <= 4. These responses set the + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3.DetectIntentResponse.response_type] + field to PARTIAL. + + For the final Nth response message, the + detect_intent_response is fully populated, and + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3.DetectIntentResponse.response_type] + is set to FINAL. """ @@ -648,7 +664,7 @@ def match_intent( self, request: Union[session.MatchIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.MatchIntentResponse: @@ -696,7 +712,7 @@ def fulfill_intent( self, request: Union[session.FulfillIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.FulfillIntentResponse: diff --git a/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py b/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py index d517dcaf..e5a0c532 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -37,15 +36,6 @@ 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 SessionsTransport(abc.ABC): """Abstract transport class for Sessions.""" @@ -98,7 +88,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -131,29 +121,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py index 8b3eaa2f..e50a87c5 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py b/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py index 8d08a189..ca62a544 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3.services.test_cases import pagers @@ -189,17 +191,17 @@ def __init__( async def list_test_cases( self, - request: test_case.ListTestCasesRequest = None, + request: Union[test_case.ListTestCasesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTestCasesAsyncPager: r"""Fetches a list of test cases for a given agent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListTestCasesRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListTestCasesRequest, dict]): The request object. The request message for [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. parent (:class:`str`): @@ -269,17 +271,17 @@ async def list_test_cases( async def batch_delete_test_cases( self, - request: test_case.BatchDeleteTestCasesRequest = None, + request: Union[test_case.BatchDeleteTestCasesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Batch deletes test cases. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest, dict]): The request object. The request message for [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases]. parent (:class:`str`): @@ -333,17 +335,17 @@ async def batch_delete_test_cases( async def get_test_case( self, - request: test_case.GetTestCaseRequest = None, + request: Union[test_case.GetTestCaseRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.TestCase: r"""Gets a test case. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetTestCaseRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetTestCaseRequest, dict]): The request object. The request message for [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3.TestCases.GetTestCase]. name (:class:`str`): @@ -402,18 +404,18 @@ async def get_test_case( async def create_test_case( self, - request: gcdc_test_case.CreateTestCaseRequest = None, + request: Union[gcdc_test_case.CreateTestCaseRequest, dict] = None, *, parent: str = None, test_case: gcdc_test_case.TestCase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_test_case.TestCase: r"""Creates a test case for the given agent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest, dict]): The request object. The request message for [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase]. parent (:class:`str`): @@ -479,18 +481,18 @@ async def create_test_case( async def update_test_case( self, - request: gcdc_test_case.UpdateTestCaseRequest = None, + request: Union[gcdc_test_case.UpdateTestCaseRequest, dict] = None, *, test_case: gcdc_test_case.TestCase = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_test_case.TestCase: r"""Updates the specified test case. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest, dict]): The request object. The request message for [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase]. test_case (:class:`google.cloud.dialogflowcx_v3.types.TestCase`): @@ -562,9 +564,9 @@ async def update_test_case( async def run_test_case( self, - request: test_case.RunTestCaseRequest = None, + request: Union[test_case.RunTestCaseRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -581,7 +583,7 @@ async def run_test_case( [RunTestCaseResponse][google.cloud.dialogflow.cx.v3.RunTestCaseResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3.types.RunTestCaseRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.RunTestCaseRequest, dict]): The request object. The request message for [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -633,9 +635,9 @@ async def run_test_case( async def batch_run_test_cases( self, - request: test_case.BatchRunTestCasesRequest = None, + request: Union[test_case.BatchRunTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -652,7 +654,7 @@ async def batch_run_test_cases( [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3.BatchRunTestCasesResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest, dict]): The request object. The request message for [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -704,16 +706,16 @@ async def batch_run_test_cases( async def calculate_coverage( self, - request: test_case.CalculateCoverageRequest = None, + request: Union[test_case.CalculateCoverageRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.CalculateCoverageResponse: r"""Calculates the test coverage for an agent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest, dict]): The request object. The request message for [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -753,9 +755,9 @@ async def calculate_coverage( async def import_test_cases( self, - request: test_case.ImportTestCasesRequest = None, + request: Union[test_case.ImportTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -775,7 +777,7 @@ async def import_test_cases( [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3.ImportTestCasesResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest, dict]): The request object. The request message for [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -827,9 +829,9 @@ async def import_test_cases( async def export_test_cases( self, - request: test_case.ExportTestCasesRequest = None, + request: Union[test_case.ExportTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -848,7 +850,7 @@ async def export_test_cases( [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3.ExportTestCasesResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest, dict]): The request object. The request message for [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -900,17 +902,17 @@ async def export_test_cases( async def list_test_case_results( self, - request: test_case.ListTestCaseResultsRequest = None, + request: Union[test_case.ListTestCaseResultsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTestCaseResultsAsyncPager: r"""Fetches a list of results for a given test case. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest, dict]): The request object. The request message for [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. parent (:class:`str`): @@ -982,17 +984,17 @@ async def list_test_case_results( async def get_test_case_result( self, - request: test_case.GetTestCaseResultRequest = None, + request: Union[test_case.GetTestCaseResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.TestCaseResult: r"""Gets a test case result. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest, dict]): The request object. The request message for [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/test_cases/client.py b/google/cloud/dialogflowcx_v3/services/test_cases/client.py index 625f08bc..1bee1287 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/client.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3.services.test_cases import pagers @@ -520,7 +522,7 @@ def list_test_cases( request: Union[test_case.ListTestCasesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTestCasesPager: @@ -600,7 +602,7 @@ def batch_delete_test_cases( request: Union[test_case.BatchDeleteTestCasesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -664,7 +666,7 @@ def get_test_case( request: Union[test_case.GetTestCaseRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.TestCase: @@ -734,7 +736,7 @@ def create_test_case( *, parent: str = None, test_case: gcdc_test_case.TestCase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_test_case.TestCase: @@ -811,7 +813,7 @@ def update_test_case( *, test_case: gcdc_test_case.TestCase = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_test_case.TestCase: @@ -892,7 +894,7 @@ def run_test_case( self, request: Union[test_case.RunTestCaseRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -964,7 +966,7 @@ def batch_run_test_cases( self, request: Union[test_case.BatchRunTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1036,7 +1038,7 @@ def calculate_coverage( self, request: Union[test_case.CalculateCoverageRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.CalculateCoverageResponse: @@ -1086,7 +1088,7 @@ def import_test_cases( self, request: Union[test_case.ImportTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1161,7 +1163,7 @@ def export_test_cases( self, request: Union[test_case.ExportTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1236,7 +1238,7 @@ def list_test_case_results( request: Union[test_case.ListTestCaseResultsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTestCaseResultsPager: @@ -1318,7 +1320,7 @@ def get_test_case_result( request: Union[test_case.GetTestCaseResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.TestCaseResult: diff --git a/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py b/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py index be3a9490..ada94e90 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 TestCasesTransport(abc.ABC): """Abstract transport class for TestCases.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { @@ -217,7 +184,7 @@ def close(self): raise NotImplementedError() @property - def operations_client(self) -> operations_v1.OperationsClient: + def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py index de41a7bf..034422fc 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py @@ -116,7 +116,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py index cb0cf723..151ae983 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py @@ -21,7 +21,6 @@ from google.api_core import operations_v1 # 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 @@ -163,7 +162,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py b/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py index b0ace91a..7858c9c0 100644 --- a/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.transition_route_groups import pagers from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import transition_route_group @@ -185,10 +187,12 @@ def __init__( async def list_transition_route_groups( self, - request: transition_route_group.ListTransitionRouteGroupsRequest = None, + request: Union[ + transition_route_group.ListTransitionRouteGroupsRequest, dict + ] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTransitionRouteGroupsAsyncPager: @@ -196,7 +200,7 @@ async def list_transition_route_groups( the specified flow. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest, dict]): The request object. The request message for [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. parent (:class:`str`): @@ -267,10 +271,12 @@ async def list_transition_route_groups( async def get_transition_route_group( self, - request: transition_route_group.GetTransitionRouteGroupRequest = None, + request: Union[ + transition_route_group.GetTransitionRouteGroupRequest, dict + ] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> transition_route_group.TransitionRouteGroup: @@ -278,7 +284,7 @@ async def get_transition_route_group( [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetTransitionRouteGroupRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetTransitionRouteGroupRequest, dict]): The request object. The request message for [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.GetTransitionRouteGroup]. name (:class:`str`): @@ -343,11 +349,13 @@ async def get_transition_route_group( async def create_transition_route_group( self, - request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, + request: Union[ + gcdc_transition_route_group.CreateTransitionRouteGroupRequest, dict + ] = None, *, parent: str = None, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_transition_route_group.TransitionRouteGroup: @@ -360,7 +368,7 @@ async def create_transition_route_group( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateTransitionRouteGroupRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateTransitionRouteGroupRequest, dict]): The request object. The request message for [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup]. parent (:class:`str`): @@ -434,11 +442,13 @@ async def create_transition_route_group( async def update_transition_route_group( self, - request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, + request: Union[ + gcdc_transition_route_group.UpdateTransitionRouteGroupRequest, dict + ] = None, *, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_transition_route_group.TransitionRouteGroup: @@ -450,7 +460,7 @@ async def update_transition_route_group( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateTransitionRouteGroupRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateTransitionRouteGroupRequest, dict]): The request object. The request message for [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.UpdateTransitionRouteGroup]. transition_route_group (:class:`google.cloud.dialogflowcx_v3.types.TransitionRouteGroup`): @@ -524,10 +534,12 @@ async def update_transition_route_group( async def delete_transition_route_group( self, - request: transition_route_group.DeleteTransitionRouteGroupRequest = None, + request: Union[ + transition_route_group.DeleteTransitionRouteGroupRequest, dict + ] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -539,7 +551,7 @@ async def delete_transition_route_group( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteTransitionRouteGroupRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteTransitionRouteGroupRequest, dict]): The request object. The request message for [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.DeleteTransitionRouteGroup]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py b/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py index 0e7c9b8c..dc2981d1 100644 --- a/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py +++ b/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.transition_route_groups import pagers from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import transition_route_group @@ -435,7 +437,7 @@ def list_transition_route_groups( ] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTransitionRouteGroupsPager: @@ -523,7 +525,7 @@ def get_transition_route_group( ] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> transition_route_group.TransitionRouteGroup: @@ -606,7 +608,7 @@ def create_transition_route_group( *, parent: str = None, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_transition_route_group.TransitionRouteGroup: @@ -705,7 +707,7 @@ def update_transition_route_group( *, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_transition_route_group.TransitionRouteGroup: @@ -802,7 +804,7 @@ def delete_transition_route_group( ] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py b/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py index 7798def7..46b31843 100644 --- a/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 TransitionRouteGroupsTransport(abc.ABC): """Abstract transport class for TransitionRouteGroups.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py index c273a12f..25a3cb89 100644 --- a/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3/services/versions/async_client.py b/google/cloud/dialogflowcx_v3/services/versions/async_client.py index b458aa98..096de9d7 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/versions/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3.services.versions import pagers @@ -165,10 +167,10 @@ def __init__( async def list_versions( self, - request: version.ListVersionsRequest = None, + request: Union[version.ListVersionsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListVersionsAsyncPager: @@ -176,7 +178,7 @@ async def list_versions( [Flow][google.cloud.dialogflow.cx.v3.Flow]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListVersionsRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListVersionsRequest, dict]): The request object. The request message for [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. parent (:class:`str`): @@ -247,10 +249,10 @@ async def list_versions( async def get_version( self, - request: version.GetVersionRequest = None, + request: Union[version.GetVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> version.Version: @@ -258,7 +260,7 @@ async def get_version( [Version][google.cloud.dialogflow.cx.v3.Version]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetVersionRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetVersionRequest, dict]): The request object. The request message for [Versions.GetVersion][google.cloud.dialogflow.cx.v3.Versions.GetVersion]. name (:class:`str`): @@ -319,11 +321,11 @@ async def get_version( async def create_version( self, - request: gcdc_version.CreateVersionRequest = None, + request: Union[gcdc_version.CreateVersionRequest, dict] = None, *, parent: str = None, version: gcdc_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -341,7 +343,7 @@ async def create_version( [Version][google.cloud.dialogflow.cx.v3.Version] Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateVersionRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateVersionRequest, dict]): The request object. The request message for [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. parent (:class:`str`): @@ -423,11 +425,11 @@ async def create_version( async def update_version( self, - request: gcdc_version.UpdateVersionRequest = None, + request: Union[gcdc_version.UpdateVersionRequest, dict] = None, *, version: gcdc_version.Version = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_version.Version: @@ -435,7 +437,7 @@ async def update_version( [Version][google.cloud.dialogflow.cx.v3.Version]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateVersionRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateVersionRequest, dict]): The request object. The request message for [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3.Versions.UpdateVersion]. version (:class:`google.cloud.dialogflowcx_v3.types.Version`): @@ -504,10 +506,10 @@ async def update_version( async def delete_version( self, - request: version.DeleteVersionRequest = None, + request: Union[version.DeleteVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -515,7 +517,7 @@ async def delete_version( [Version][google.cloud.dialogflow.cx.v3.Version]. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteVersionRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteVersionRequest, dict]): The request object. The request message for [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3.Versions.DeleteVersion]. name (:class:`str`): @@ -571,10 +573,10 @@ async def delete_version( async def load_version( self, - request: version.LoadVersionRequest = None, + request: Union[version.LoadVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -591,7 +593,7 @@ async def load_version( message `__ Args: - request (:class:`google.cloud.dialogflowcx_v3.types.LoadVersionRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.LoadVersionRequest, dict]): The request object. The request message for [Versions.LoadVersion][google.cloud.dialogflow.cx.v3.Versions.LoadVersion]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/versions/client.py b/google/cloud/dialogflowcx_v3/services/versions/client.py index 3bcad503..9928017a 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/client.py +++ b/google/cloud/dialogflowcx_v3/services/versions/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3.services.versions import pagers @@ -362,7 +364,7 @@ def list_versions( request: Union[version.ListVersionsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListVersionsPager: @@ -444,7 +446,7 @@ def get_version( request: Union[version.GetVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> version.Version: @@ -517,7 +519,7 @@ def create_version( *, parent: str = None, version: gcdc_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -621,7 +623,7 @@ def update_version( *, version: gcdc_version.Version = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_version.Version: @@ -701,7 +703,7 @@ def delete_version( request: Union[version.DeleteVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -768,7 +770,7 @@ def load_version( request: Union[version.LoadVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: diff --git a/google/cloud/dialogflowcx_v3/services/versions/transports/base.py b/google/cloud/dialogflowcx_v3/services/versions/transports/base.py index b9db41c2..328ab113 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/versions/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 VersionsTransport(abc.ABC): """Abstract transport class for Versions.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { @@ -191,7 +158,7 @@ def close(self): raise NotImplementedError() @property - def operations_client(self) -> operations_v1.OperationsClient: + def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py index dd63a7f7..e6dc88a1 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py @@ -115,7 +115,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py index 73fa667a..336d56e7 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py @@ -21,7 +21,6 @@ from google.api_core import operations_v1 # 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 @@ -162,7 +161,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py b/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py index 58acdf0f..f1b291df 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.webhooks import pagers from google.cloud.dialogflowcx_v3.types import webhook from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook @@ -162,10 +164,10 @@ def __init__( async def list_webhooks( self, - request: webhook.ListWebhooksRequest = None, + request: Union[webhook.ListWebhooksRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListWebhooksAsyncPager: @@ -173,7 +175,7 @@ async def list_webhooks( agent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListWebhooksRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.ListWebhooksRequest, dict]): The request object. The request message for [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. parent (:class:`str`): @@ -243,17 +245,17 @@ async def list_webhooks( async def get_webhook( self, - request: webhook.GetWebhookRequest = None, + request: Union[webhook.GetWebhookRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> webhook.Webhook: r"""Retrieves the specified webhook. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetWebhookRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.GetWebhookRequest, dict]): The request object. The request message for [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3.Webhooks.GetWebhook]. name (:class:`str`): @@ -319,18 +321,18 @@ async def get_webhook( async def create_webhook( self, - request: gcdc_webhook.CreateWebhookRequest = None, + request: Union[gcdc_webhook.CreateWebhookRequest, dict] = None, *, parent: str = None, webhook: gcdc_webhook.Webhook = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_webhook.Webhook: r"""Creates a webhook in the specified agent. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateWebhookRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.CreateWebhookRequest, dict]): The request object. The request message for [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook]. parent (:class:`str`): @@ -403,18 +405,18 @@ async def create_webhook( async def update_webhook( self, - request: gcdc_webhook.UpdateWebhookRequest = None, + request: Union[gcdc_webhook.UpdateWebhookRequest, dict] = None, *, webhook: gcdc_webhook.Webhook = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_webhook.Webhook: r"""Updates the specified webhook. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateWebhookRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.UpdateWebhookRequest, dict]): The request object. The request message for [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook]. webhook (:class:`google.cloud.dialogflowcx_v3.types.Webhook`): @@ -490,17 +492,17 @@ async def update_webhook( async def delete_webhook( self, - request: webhook.DeleteWebhookRequest = None, + request: Union[webhook.DeleteWebhookRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified webhook. Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteWebhookRequest`): + request (Union[google.cloud.dialogflowcx_v3.types.DeleteWebhookRequest, dict]): The request object. The request message for [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3.Webhooks.DeleteWebhook]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/client.py b/google/cloud/dialogflowcx_v3/services/webhooks/client.py index d96cefbe..d08d2df2 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/client.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3.services.webhooks import pagers from google.cloud.dialogflowcx_v3.types import webhook from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook @@ -371,7 +373,7 @@ def list_webhooks( request: Union[webhook.ListWebhooksRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListWebhooksPager: @@ -452,7 +454,7 @@ def get_webhook( request: Union[webhook.GetWebhookRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> webhook.Webhook: @@ -529,7 +531,7 @@ def create_webhook( *, parent: str = None, webhook: gcdc_webhook.Webhook = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_webhook.Webhook: @@ -613,7 +615,7 @@ def update_webhook( *, webhook: gcdc_webhook.Webhook = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_webhook.Webhook: @@ -699,7 +701,7 @@ def delete_webhook( request: Union[webhook.DeleteWebhookRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py b/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py index 54aaa09d..c81846c0 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -39,15 +38,6 @@ 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 WebhooksTransport(abc.ABC): """Abstract transport class for Webhooks.""" @@ -100,7 +90,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -133,29 +123,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py index 2177a890..0f6c7fbd 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3/types/__init__.py b/google/cloud/dialogflowcx_v3/types/__init__.py index b81c76bd..81aaa5cd 100644 --- a/google/cloud/dialogflowcx_v3/types/__init__.py +++ b/google/cloud/dialogflowcx_v3/types/__init__.py @@ -41,6 +41,12 @@ SpeechModelVariant, SsmlVoiceGender, ) +from .changelog import ( + Changelog, + GetChangelogRequest, + ListChangelogsRequest, + ListChangelogsResponse, +) from .deployment import ( Deployment, GetDeploymentRequest, @@ -271,6 +277,10 @@ "OutputAudioEncoding", "SpeechModelVariant", "SsmlVoiceGender", + "Changelog", + "GetChangelogRequest", + "ListChangelogsRequest", + "ListChangelogsResponse", "Deployment", "GetDeploymentRequest", "ListDeploymentsRequest", diff --git a/google/cloud/dialogflowcx_v3/types/agent.py b/google/cloud/dialogflowcx_v3/types/agent.py index e1ebbea3..c7918174 100644 --- a/google/cloud/dialogflowcx_v3/types/agent.py +++ b/google/cloud/dialogflowcx_v3/types/agent.py @@ -284,13 +284,22 @@ class ExportAgentResponse(proto.Message): r"""The response message for [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: agent_uri (str): The URI to a file containing the exported agent. This field is populated only if ``agent_uri`` is specified in [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest]. + This field is a member of `oneof`_ ``agent``. agent_content (bytes): Uncompressed raw byte content for agent. + This field is a member of `oneof`_ ``agent``. """ agent_uri = proto.Field(proto.STRING, number=1, oneof="agent",) @@ -301,6 +310,13 @@ class RestoreAgentRequest(proto.Message): r"""The request message for [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Required. The name of the agent to restore into. Format: @@ -310,8 +326,10 @@ class RestoreAgentRequest(proto.Message): Storage `__ URI to restore agent from. The format of this URI must be ``gs:///``. + This field is a member of `oneof`_ ``agent``. agent_content (bytes): Uncompressed raw byte content for agent. + This field is a member of `oneof`_ ``agent``. restore_option (google.cloud.dialogflowcx_v3.types.RestoreAgentRequest.RestoreOption): Agent restore mode. If not specified, ``KEEP`` is assumed. """ diff --git a/google/cloud/dialogflowcx_v3/types/changelog.py b/google/cloud/dialogflowcx_v3/types/changelog.py new file mode 100644 index 00000000..a58f7390 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/types/changelog.py @@ -0,0 +1,139 @@ +# -*- 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.v3", + manifest={ + "ListChangelogsRequest", + "ListChangelogsResponse", + "GetChangelogRequest", + "Changelog", + }, +) + + +class ListChangelogsRequest(proto.Message): + r"""The request message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3.Changelogs.ListChangelogs]. + + Attributes: + parent (str): + Required. The agent containing the changelogs. Format: + ``projects//locations//agents/``. + filter (str): + The filter string. Supports filter by user_email, resource, + type and create_time. Some examples: + + 1. By user email: user_email = "someone@google.com" + 2. By resource name: resource = + "projects/123/locations/global/agents/456/flows/789" + 3. By resource display name: display_name = "my agent" + 4. By action: action = "Create" + 5. By type: type = "flows" + 6. By create time. Currently predicates on ``create_time`` + and ``create_time_epoch_seconds`` are supported: + create_time_epoch_seconds > 1551790877 AND create_time <= + 2017-01-15T01:30:15.01Z + 7. Combination of above filters: resource = + "projects/123/locations/global/agents/456/flows/789" AND + user_email = "someone@google.com" AND create_time <= + 2017-01-15T01:30:15.01Z + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) + + +class ListChangelogsResponse(proto.Message): + r"""The response message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3.Changelogs.ListChangelogs]. + + Attributes: + changelogs (Sequence[google.cloud.dialogflowcx_v3.types.Changelog]): + The list of changelogs. There will be a maximum number of + items returned based on the page_size field in the request. + The changelogs will be ordered by timestamp. + 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 + + changelogs = proto.RepeatedField(proto.MESSAGE, number=1, message="Changelog",) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetChangelogRequest(proto.Message): + r"""The request message for + [Changelogs.GetChangelog][google.cloud.dialogflow.cx.v3.Changelogs.GetChangelog]. + + Attributes: + name (str): + Required. The name of the changelog to get. Format: + ``projects//locations//agents//changelogs/``. + """ + + name = proto.Field(proto.STRING, number=1,) + + +class Changelog(proto.Message): + r"""Changelogs represents a change made to a given agent. + + Attributes: + name (str): + The unique identifier of the changelog. Format: + ``projects//locations//agents//changelogs/``. + user_email (str): + Email address of the authenticated user. + display_name (str): + The affected resource display name of the + change. + action (str): + The action of the change. + type_ (str): + The affected resource type. + resource (str): + The affected resource name of the change. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of the change. + """ + + name = proto.Field(proto.STRING, number=1,) + user_email = proto.Field(proto.STRING, number=2,) + display_name = proto.Field(proto.STRING, number=7,) + action = proto.Field(proto.STRING, number=11,) + type_ = proto.Field(proto.STRING, number=8,) + resource = proto.Field(proto.STRING, number=3,) + create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/experiment.py b/google/cloud/dialogflowcx_v3/types/experiment.py index 96f95be9..59fd4ef0 100644 --- a/google/cloud/dialogflowcx_v3/types/experiment.py +++ b/google/cloud/dialogflowcx_v3/types/experiment.py @@ -112,6 +112,8 @@ class State(proto.Enum): class Definition(proto.Message): r"""Definition of the experiment. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: condition (str): The condition defines which subset of sessions are selected @@ -122,6 +124,7 @@ class Definition(proto.Message): version_variants (google.cloud.dialogflowcx_v3.types.VersionVariants): The flow versions as the variants of this experiment. + This field is a member of `oneof`_ ``variants``. """ condition = proto.Field(proto.STRING, number=1,) @@ -184,6 +187,13 @@ class ConfidenceInterval(proto.Message): class Metric(proto.Message): r"""Metric and corresponding confidence intervals. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: type_ (google.cloud.dialogflowcx_v3.types.Experiment.Result.MetricType): Ratio-based metric type. Only one of type or count_type is @@ -193,8 +203,10 @@ class Metric(proto.Message): specified in each Metric. ratio (float): Ratio value of a metric. + This field is a member of `oneof`_ ``value``. count (float): Count value of a metric. + This field is a member of `oneof`_ ``value``. confidence_interval (google.cloud.dialogflowcx_v3.types.Experiment.Result.ConfidenceInterval): The probability that the treatment is better than all other treatments in the experiment @@ -297,9 +309,12 @@ class Variant(proto.Message): class VariantsHistory(proto.Message): r"""The history of variants update. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: version_variants (google.cloud.dialogflowcx_v3.types.VersionVariants): The flow versions as the variants. + This field is a member of `oneof`_ ``variants``. update_time (google.protobuf.timestamp_pb2.Timestamp): Update time of the variants. """ diff --git a/google/cloud/dialogflowcx_v3/types/flow.py b/google/cloud/dialogflowcx_v3/types/flow.py index ccea05c0..1be857dc 100644 --- a/google/cloud/dialogflowcx_v3/types/flow.py +++ b/google/cloud/dialogflowcx_v3/types/flow.py @@ -420,6 +420,13 @@ class ImportFlowRequest(proto.Message): r"""The request message for [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: parent (str): Required. The agent to import the flow into. Format: @@ -429,8 +436,10 @@ class ImportFlowRequest(proto.Message): Storage `__ URI to import flow from. The format of this URI must be ``gs:///``. + This field is a member of `oneof`_ ``flow``. flow_content (bytes): Uncompressed raw byte content for flow. + This field is a member of `oneof`_ ``flow``. import_option (google.cloud.dialogflowcx_v3.types.ImportFlowRequest.ImportOption): Flow import mode. If not specified, ``KEEP`` is assumed. """ @@ -488,13 +497,22 @@ class ExportFlowResponse(proto.Message): r"""The response message for [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: flow_uri (str): The URI to a file containing the exported flow. This field is populated only if ``flow_uri`` is specified in [ExportFlowRequest][google.cloud.dialogflow.cx.v3.ExportFlowRequest]. + This field is a member of `oneof`_ ``flow``. flow_content (bytes): Uncompressed raw byte content for flow. + This field is a member of `oneof`_ ``flow``. """ flow_uri = proto.Field(proto.STRING, number=1, oneof="flow",) diff --git a/google/cloud/dialogflowcx_v3/types/fulfillment.py b/google/cloud/dialogflowcx_v3/types/fulfillment.py index f7c4c2c7..684fa89b 100644 --- a/google/cloud/dialogflowcx_v3/types/fulfillment.py +++ b/google/cloud/dialogflowcx_v3/types/fulfillment.py @@ -122,11 +122,20 @@ class CaseContent(proto.Message): r"""The list of messages or conditional cases to activate for this case. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: message (google.cloud.dialogflowcx_v3.types.ResponseMessage): Returned message. + This field is a member of `oneof`_ ``cases_or_message``. additional_cases (google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases): Additional cases to be evaluated. + This field is a member of `oneof`_ ``cases_or_message``. """ message = proto.Field( diff --git a/google/cloud/dialogflowcx_v3/types/page.py b/google/cloud/dialogflowcx_v3/types/page.py index 1fd2959d..6472c4de 100644 --- a/google/cloud/dialogflowcx_v3/types/page.py +++ b/google/cloud/dialogflowcx_v3/types/page.py @@ -276,6 +276,13 @@ class EventHandler(proto.Message): associated with the event, the session will transition into the specified flow. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Output only. The unique identifier of this @@ -291,9 +298,11 @@ class EventHandler(proto.Message): target_page (str): The target page to transition to. Format: ``projects//locations//agents//flows//pages/``. + This field is a member of `oneof`_ ``target``. target_flow (str): The target flow to transition to. Format: ``projects//locations//agents//flows/``. + This field is a member of `oneof`_ ``target``. """ name = proto.Field(proto.STRING, number=6,) @@ -324,6 +333,13 @@ class TransitionRoute(proto.Message): associated with the transition, the session will transition into the specified flow. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Output only. The unique identifier of this @@ -357,9 +373,11 @@ class TransitionRoute(proto.Message): target_page (str): The target page to transition to. Format: ``projects//locations//agents//flows//pages/``. + This field is a member of `oneof`_ ``target``. target_flow (str): The target flow to transition to. Format: ``projects//locations//agents//flows/``. + This field is a member of `oneof`_ ``target``. """ name = proto.Field(proto.STRING, number=6,) diff --git a/google/cloud/dialogflowcx_v3/types/response_message.py b/google/cloud/dialogflowcx_v3/types/response_message.py index bd98944f..4d912bff 100644 --- a/google/cloud/dialogflowcx_v3/types/response_message.py +++ b/google/cloud/dialogflowcx_v3/types/response_message.py @@ -45,21 +45,33 @@ class ResponseMessage(proto.Message): scenarios, where the text displayed to the user may differ from what is heard. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: text (google.cloud.dialogflowcx_v3.types.ResponseMessage.Text): Returns a text response. + This field is a member of `oneof`_ ``message``. payload (google.protobuf.struct_pb2.Struct): Returns a response containing a custom, platform-specific payload. + This field is a member of `oneof`_ ``message``. conversation_success (google.cloud.dialogflowcx_v3.types.ResponseMessage.ConversationSuccess): Indicates that the conversation succeeded. + This field is a member of `oneof`_ ``message``. output_audio_text (google.cloud.dialogflowcx_v3.types.ResponseMessage.OutputAudioText): A text or ssml response that is preferentially used for TTS output audio synthesis, as described in the comment on the ResponseMessage message. + This field is a member of `oneof`_ ``message``. live_agent_handoff (google.cloud.dialogflowcx_v3.types.ResponseMessage.LiveAgentHandoff): Hands off conversation to a human agent. + This field is a member of `oneof`_ ``message``. end_interaction (google.cloud.dialogflowcx_v3.types.ResponseMessage.EndInteraction): Output only. A signal that indicates the interaction with the Dialogflow agent has ended. This message is generated by @@ -69,12 +81,14 @@ class ResponseMessage(proto.Message): It's guaranteed that there is at most one such message in each response. + This field is a member of `oneof`_ ``message``. play_audio (google.cloud.dialogflowcx_v3.types.ResponseMessage.PlayAudio): Signal that the client should play an audio clip hosted at a client-specific URI. Dialogflow uses this to construct [mixed_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.mixed_audio]. However, Dialogflow itself does not try to read or process the URI in any way. + This field is a member of `oneof`_ ``message``. mixed_audio (google.cloud.dialogflowcx_v3.types.ResponseMessage.MixedAudio): Output only. An audio response message composed of both the synthesized Dialogflow agent responses and responses defined @@ -82,6 +96,7 @@ class ResponseMessage(proto.Message): [play_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.play_audio]. This message is generated by Dialogflow only and not supposed to be defined by the user. + This field is a member of `oneof`_ ``message``. """ class Text(proto.Message): @@ -159,12 +174,21 @@ class OutputAudioText(proto.Message): output audio synthesis, as described in the comment on the ResponseMessage message. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: text (str): The raw text to be synthesized. + This field is a member of `oneof`_ ``source``. ssml (str): The SSML text to be synthesized. For more information, see `SSML `__. + This field is a member of `oneof`_ ``source``. allow_playback_interruption (bool): Output only. Whether the playback of this message can be interrupted by the end user's @@ -219,15 +243,24 @@ class MixedAudio(proto.Message): class Segment(proto.Message): r"""Represents one segment of audio. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: audio (bytes): Raw audio synthesized from the Dialogflow agent's response using the output config specified in the request. + This field is a member of `oneof`_ ``content``. uri (str): Client-specific URI that points to an audio clip accessible to the client. Dialogflow does not impose any validation on it. + This field is a member of `oneof`_ ``content``. allow_playback_interruption (bool): Output only. Whether the playback of this segment can be interrupted by the end user's diff --git a/google/cloud/dialogflowcx_v3/types/security_settings.py b/google/cloud/dialogflowcx_v3/types/security_settings.py index c93daef2..a557d382 100644 --- a/google/cloud/dialogflowcx_v3/types/security_settings.py +++ b/google/cloud/dialogflowcx_v3/types/security_settings.py @@ -148,6 +148,9 @@ class SecuritySettings(proto.Message): on the settings to propagate to all the related components and take effect. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Resource name of the settings. Required for the @@ -207,6 +210,7 @@ class SecuritySettings(proto.Message): Note: Interaction logging is a limited access feature. Talk to your Google representative to check availability for you. + This field is a member of `oneof`_ ``data_retention``. purge_data_types (Sequence[google.cloud.dialogflowcx_v3.types.SecuritySettings.PurgeDataType]): List of types of data to remove when retention settings triggers purge. diff --git a/google/cloud/dialogflowcx_v3/types/session.py b/google/cloud/dialogflowcx_v3/types/session.py index c3ce26f7..b03eecc5 100644 --- a/google/cloud/dialogflowcx_v3/types/session.py +++ b/google/cloud/dialogflowcx_v3/types/session.py @@ -223,30 +223,49 @@ class StreamingDetectIntentRequest(proto.Message): class StreamingDetectIntentResponse(proto.Message): - r"""The top-level message returned from the ``StreamingDetectIntent`` + r"""The top-level message returned from the + [StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] method. - Multiple response messages can be returned in order: + Multiple response messages (N) can be returned in order. - 1. If the input was set to streaming audio, the first one or more - messages contain ``recognition_result``. Each - ``recognition_result`` represents a more complete transcript of - what the user said. The last ``recognition_result`` has - ``is_final`` set to ``true``. + The first (N-1) responses set either the ``recognition_result`` or + ``detect_intent_response`` field, depending on the request: - 2. If ``enable_partial_response`` is true, the following N messages - (currently 1 <= N <= 4) contain ``detect_intent_response``. The - first (N-1) ``detect_intent_response``\ s will have - ``response_type`` set to ``PARTIAL``. The last - ``detect_intent_response`` has ``response_type`` set to - ``FINAL``. If ``response_type`` is false, response stream only - contains the final ``detect_intent_response``. + - If the ``StreamingDetectIntentRequest.query_input.audio`` field + was set, and the + ``StreamingDetectIntentRequest.enable_partial_response`` field + was false, the ``recognition_result`` field is populated for each + of the (N-1) responses. See the + [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3.StreamingRecognitionResult] + message for details about the result message sequence. + + - If the ``StreamingDetectIntentRequest.enable_partial_response`` + field was true, the ``detect_intent_response`` field is populated + for each of the (N-1) responses, where 1 <= N <= 4. These + responses set the + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3.DetectIntentResponse.response_type] + field to ``PARTIAL``. + + For the final Nth response message, the ``detect_intent_response`` + is fully populated, and + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3.DetectIntentResponse.response_type] + is set to ``FINAL``. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: recognition_result (google.cloud.dialogflowcx_v3.types.StreamingRecognitionResult): The result of speech recognition. + This field is a member of `oneof`_ ``response``. detect_intent_response (google.cloud.dialogflowcx_v3.types.DetectIntentResponse): The response from detect intent. + This field is a member of `oneof`_ ``response``. """ recognition_result = proto.Field( @@ -262,33 +281,42 @@ class StreamingRecognitionResult(proto.Message): the audio that is currently being processed or an indication that this is the end of the single requested utterance. - Example: - - 1. transcript: "tube" - - 2. transcript: "to be a" - - 3. transcript: "to be" - - 4. transcript: "to be or not to be" is_final: true - - 5. transcript: " that's" - - 6. transcript: " that is" - - 7. message_type: ``END_OF_SINGLE_UTTERANCE`` - - 8. transcript: " that is the question" is_final: true - - Only two of the responses contain final results (#4 and #8 indicated - by ``is_final: true``). Concatenating these generates the full - transcript: "to be or not to be that is the question". - - In each response we populate: - - - for ``TRANSCRIPT``: ``transcript`` and possibly ``is_final``. - - - for ``END_OF_SINGLE_UTTERANCE``: only ``message_type``. + While end-user audio is being processed, Dialogflow sends a series + of results. Each result may contain a ``transcript`` value. A + transcript represents a portion of the utterance. While the + recognizer is processing audio, transcript values may be interim + values or finalized values. Once a transcript is finalized, the + ``is_final`` value is set to true and processing continues for the + next transcript. + + If + ``StreamingDetectIntentRequest.query_input.audio.config.single_utterance`` + was true, and the recognizer has completed processing audio, the + ``message_type`` value is set to \`END_OF_SINGLE_UTTERANCE and the + following (last) result contains the last finalized transcript. + + The complete end-user utterance is determined by concatenating the + finalized transcript values received for the series of results. + + In the following example, single utterance is enabled. In the case + where single utterance is not enabled, result 7 would not occur. + + :: + + Num | transcript | message_type | is_final + --- | ----------------------- | ----------------------- | -------- + 1 | "tube" | TRANSCRIPT | false + 2 | "to be a" | TRANSCRIPT | false + 3 | "to be" | TRANSCRIPT | false + 4 | "to be or not to be" | TRANSCRIPT | true + 5 | "that's" | TRANSCRIPT | false + 6 | "that is | TRANSCRIPT | false + 7 | unset | END_OF_SINGLE_UTTERANCE | unset + 8 | " that is the question" | TRANSCRIPT | true + + Concatenating the finalized transcripts with ``is_final`` set to + true, the complete utterance becomes "to be or not to be that is the + question". Attributes: message_type (google.cloud.dialogflowcx_v3.types.StreamingRecognitionResult.MessageType): @@ -486,18 +514,30 @@ class QueryInput(proto.Message): 4. An event to be triggered. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: text (google.cloud.dialogflowcx_v3.types.TextInput): The natural language text to be processed. + This field is a member of `oneof`_ ``input``. intent (google.cloud.dialogflowcx_v3.types.IntentInput): The intent to be triggered. + This field is a member of `oneof`_ ``input``. audio (google.cloud.dialogflowcx_v3.types.AudioInput): The natural language speech audio to be processed. + This field is a member of `oneof`_ ``input``. event (google.cloud.dialogflowcx_v3.types.EventInput): The event to be triggered. + This field is a member of `oneof`_ ``input``. dtmf (google.cloud.dialogflowcx_v3.types.DtmfInput): The DTMF event to be handled. + This field is a member of `oneof`_ ``input``. language_code (str): Required. The language of the input. See `Language Support `__ @@ -517,28 +557,40 @@ class QueryInput(proto.Message): class QueryResult(proto.Message): r"""Represents the result of a conversational query. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: text (str): If [natural language text][google.cloud.dialogflow.cx.v3.TextInput] was provided as input, this field will contain a copy of the text. + This field is a member of `oneof`_ ``query``. trigger_intent (str): If an [intent][google.cloud.dialogflow.cx.v3.IntentInput] was provided as input, this field will contain a copy of the intent identifier. Format: ``projects//locations//agents//intents/``. + This field is a member of `oneof`_ ``query``. transcript (str): If [natural language speech audio][google.cloud.dialogflow.cx.v3.AudioInput] was provided as input, this field will contain the transcript for the audio. + This field is a member of `oneof`_ ``query``. trigger_event (str): If an [event][google.cloud.dialogflow.cx.v3.EventInput] was provided as input, this field will contain the name of the event. + This field is a member of `oneof`_ ``query``. dtmf (google.cloud.dialogflowcx_v3.types.DtmfInput): If a [DTMF][DTMFInput] was provided as input, this field will contain a copy of the [DTMFInput][]. + This field is a member of `oneof`_ ``query``. language_code (str): The language that was triggered during intent detection. See `Language @@ -825,25 +877,36 @@ class MatchIntentRequest(proto.Message): class MatchIntentResponse(proto.Message): r"""Response of [MatchIntent][]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: text (str): If [natural language text][google.cloud.dialogflow.cx.v3.TextInput] was provided as input, this field will contain a copy of the text. + This field is a member of `oneof`_ ``query``. trigger_intent (str): If an [intent][google.cloud.dialogflow.cx.v3.IntentInput] was provided as input, this field will contain a copy of the intent identifier. Format: ``projects//locations//agents//intents/``. + This field is a member of `oneof`_ ``query``. transcript (str): If [natural language speech audio][google.cloud.dialogflow.cx.v3.AudioInput] was provided as input, this field will contain the transcript for the audio. + This field is a member of `oneof`_ ``query``. trigger_event (str): If an [event][google.cloud.dialogflow.cx.v3.EventInput] was provided as input, this field will contain a copy of the event name. + This field is a member of `oneof`_ ``query``. matches (Sequence[google.cloud.dialogflowcx_v3.types.Match]): Match results, if more than one, ordered descendingly by the confidence we have that the diff --git a/google/cloud/dialogflowcx_v3/types/test_case.py b/google/cloud/dialogflowcx_v3/types/test_case.py index d94495af..2691cf93 100644 --- a/google/cloud/dialogflowcx_v3/types/test_case.py +++ b/google/cloud/dialogflowcx_v3/types/test_case.py @@ -310,15 +310,24 @@ class TransitionCoverage(proto.Message): class TransitionNode(proto.Message): r"""The source or target of a transition. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: page (google.cloud.dialogflowcx_v3.types.Page): Indicates a transition to a [Page][google.cloud.dialogflow.cx.v3.Page]. Only some fields such as name and displayname will be set. + This field is a member of `oneof`_ ``kind``. flow (google.cloud.dialogflowcx_v3.types.Flow): Indicates a transition to a [Flow][google.cloud.dialogflow.cx.v3.Flow]. Only some fields such as name and displayname will be set. + This field is a member of `oneof`_ ``kind``. """ page = proto.Field( @@ -331,6 +340,13 @@ class TransitionNode(proto.Message): class Transition(proto.Message): r"""A transition in a page. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: source (google.cloud.dialogflowcx_v3.types.TransitionCoverage.TransitionNode): The start node of a transition. @@ -344,8 +360,10 @@ class Transition(proto.Message): at least one of the agent's test cases. transition_route (google.cloud.dialogflowcx_v3.types.TransitionRoute): Intent route or condition route. + This field is a member of `oneof`_ ``detail``. event_handler (google.cloud.dialogflowcx_v3.types.EventHandler): Event handler. + This field is a member of `oneof`_ ``detail``. """ source = proto.Field( @@ -487,17 +505,27 @@ class CalculateCoverageResponse(proto.Message): r"""The response message for [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: agent (str): The agent to calculate coverage for. Format: ``projects//locations//agents/``. intent_coverage (google.cloud.dialogflowcx_v3.types.IntentCoverage): Intent coverage. + This field is a member of `oneof`_ ``coverage_type``. transition_coverage (google.cloud.dialogflowcx_v3.types.TransitionCoverage): Transition (excluding transition route groups) coverage. + This field is a member of `oneof`_ ``coverage_type``. route_group_coverage (google.cloud.dialogflowcx_v3.types.TransitionRouteGroupCoverage): Transition route group coverage. + This field is a member of `oneof`_ ``coverage_type``. """ agent = proto.Field(proto.STRING, number=5,) @@ -748,6 +776,13 @@ class ImportTestCasesRequest(proto.Message): r"""The request message for [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: parent (str): Required. The agent to import test cases to. Format: @@ -757,8 +792,10 @@ class ImportTestCasesRequest(proto.Message): Storage `__ URI to import test cases from. The format of this URI must be ``gs:///``. + This field is a member of `oneof`_ ``source``. content (bytes): Uncompressed raw byte content for test cases. + This field is a member of `oneof`_ ``source``. """ parent = proto.Field(proto.STRING, number=1,) @@ -810,6 +847,9 @@ class ExportTestCasesRequest(proto.Message): r"""The request message for [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: parent (str): Required. The agent where to export test cases from. Format: @@ -820,6 +860,7 @@ class ExportTestCasesRequest(proto.Message): export the test cases to. The format of this URI must be ``gs:///``. If unspecified, the serialized test cases is returned inline. + This field is a member of `oneof`_ ``destination``. data_format (google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest.DataFormat): The data format of the exported test cases. If not specified, ``BLOB`` is assumed. @@ -852,13 +893,22 @@ class ExportTestCasesResponse(proto.Message): r"""The response message for [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: gcs_uri (str): The URI to a file containing the exported test cases. This field is populated only if ``gcs_uri`` is specified in [ExportTestCasesRequest][google.cloud.dialogflow.cx.v3.ExportTestCasesRequest]. + This field is a member of `oneof`_ ``destination``. content (bytes): Uncompressed raw byte content for test cases. + This field is a member of `oneof`_ ``destination``. """ gcs_uri = proto.Field(proto.STRING, number=1, oneof="destination",) diff --git a/google/cloud/dialogflowcx_v3/types/webhook.py b/google/cloud/dialogflowcx_v3/types/webhook.py index d16dff00..66e12852 100644 --- a/google/cloud/dialogflowcx_v3/types/webhook.py +++ b/google/cloud/dialogflowcx_v3/types/webhook.py @@ -46,6 +46,13 @@ class Webhook(proto.Message): responses, validate collected data, or trigger actions on the backend. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): The unique identifier of the webhook. Required for the @@ -59,10 +66,12 @@ class Webhook(proto.Message): webhook, unique within the agent. generic_web_service (google.cloud.dialogflowcx_v3.types.Webhook.GenericWebService): Configuration for a generic web service. + This field is a member of `oneof`_ ``webhook``. service_directory (google.cloud.dialogflowcx_v3.types.Webhook.ServiceDirectoryConfig): Configuration for a `Service Directory `__ service. + This field is a member of `oneof`_ ``webhook``. timeout (google.protobuf.duration_pb2.Duration): Webhook execution timeout. Execution is considered failed if Dialogflow doesn't receive @@ -251,6 +260,13 @@ class WebhookRequest(proto.Message): as a JSON object and the field names will be presented in camel cases. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: detect_intent_response_id (str): Always present. The unique identifier of the @@ -260,20 +276,24 @@ class WebhookRequest(proto.Message): If [natural language text][google.cloud.dialogflow.cx.v3.TextInput] was provided as input, this field will contain a copy of the text. + This field is a member of `oneof`_ ``query``. trigger_intent (str): If an [intent][google.cloud.dialogflow.cx.v3.IntentInput] was provided as input, this field will contain a copy of the intent identifier. Format: ``projects//locations//agents//intents/``. + This field is a member of `oneof`_ ``query``. transcript (str): If [natural language speech audio][google.cloud.dialogflow.cx.v3.AudioInput] was provided as input, this field will contain the transcript for the audio. + This field is a member of `oneof`_ ``query``. trigger_event (str): If an [event][google.cloud.dialogflow.cx.v3.EventInput] was provided as input, this field will contain the name of the event. + This field is a member of `oneof`_ ``query``. language_code (str): The language code specified in the [original request][QueryInput.language_code]. @@ -401,6 +421,13 @@ class SentimentAnalysisResult(proto.Message): class WebhookResponse(proto.Message): r"""The response message for a webhook call. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: fulfillment_response (google.cloud.dialogflowcx_v3.types.WebhookResponse.FulfillmentResponse): The fulfillment response to send to the user. @@ -421,9 +448,11 @@ class WebhookResponse(proto.Message): target_page (str): The target page to transition to. Format: ``projects//locations//agents//flows//pages/``. + This field is a member of `oneof`_ ``transition``. target_flow (str): The target flow to transition to. Format: ``projects//locations//agents//flows/``. + This field is a member of `oneof`_ ``transition``. """ class FulfillmentResponse(proto.Message): diff --git a/google/cloud/dialogflowcx_v3beta1/__init__.py b/google/cloud/dialogflowcx_v3beta1/__init__.py index f404f8ff..e2126f7a 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.changelogs import ChangelogsClient +from .services.changelogs import ChangelogsAsyncClient from .services.deployments import DeploymentsClient from .services.deployments import DeploymentsAsyncClient from .services.entity_types import EntityTypesClient @@ -69,6 +71,10 @@ from .types.audio_config import OutputAudioEncoding from .types.audio_config import SpeechModelVariant from .types.audio_config import SsmlVoiceGender +from .types.changelog import Changelog +from .types.changelog import GetChangelogRequest +from .types.changelog import ListChangelogsRequest +from .types.changelog import ListChangelogsResponse from .types.deployment import Deployment from .types.deployment import GetDeploymentRequest from .types.deployment import ListDeploymentsRequest @@ -223,6 +229,8 @@ from .types.transition_route_group import UpdateTransitionRouteGroupRequest from .types.validation_message import ResourceName from .types.validation_message import ValidationMessage +from .types.version import CompareVersionsRequest +from .types.version import CompareVersionsResponse from .types.version import CreateVersionOperationMetadata from .types.version import CreateVersionRequest from .types.version import DeleteVersionRequest @@ -246,6 +254,7 @@ __all__ = ( "AgentsAsyncClient", + "ChangelogsAsyncClient", "DeploymentsAsyncClient", "EntityTypesAsyncClient", "EnvironmentsAsyncClient", @@ -272,6 +281,10 @@ "BatchRunTestCasesResponse", "CalculateCoverageRequest", "CalculateCoverageResponse", + "Changelog", + "ChangelogsClient", + "CompareVersionsRequest", + "CompareVersionsResponse", "ContinuousTestResult", "ConversationTurn", "CreateAgentRequest", @@ -332,6 +345,7 @@ "Fulfillment", "GetAgentRequest", "GetAgentValidationResultRequest", + "GetChangelogRequest", "GetDeploymentRequest", "GetEntityTypeRequest", "GetEnvironmentRequest", @@ -360,6 +374,8 @@ "IntentsClient", "ListAgentsRequest", "ListAgentsResponse", + "ListChangelogsRequest", + "ListChangelogsResponse", "ListContinuousTestResultsRequest", "ListContinuousTestResultsResponse", "ListDeploymentsRequest", diff --git a/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json b/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json index 4225947d..a59ccd58 100644 --- a/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json +++ b/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json @@ -109,6 +109,40 @@ } } }, + "Changelogs": { + "clients": { + "grpc": { + "libraryClient": "ChangelogsClient", + "rpcs": { + "GetChangelog": { + "methods": [ + "get_changelog" + ] + }, + "ListChangelogs": { + "methods": [ + "list_changelogs" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ChangelogsAsyncClient", + "rpcs": { + "GetChangelog": { + "methods": [ + "get_changelog" + ] + }, + "ListChangelogs": { + "methods": [ + "list_changelogs" + ] + } + } + } + } + }, "Deployments": { "clients": { "grpc": { @@ -1022,6 +1056,11 @@ "grpc": { "libraryClient": "VersionsClient", "rpcs": { + "CompareVersions": { + "methods": [ + "compare_versions" + ] + }, "CreateVersion": { "methods": [ "create_version" @@ -1057,6 +1096,11 @@ "grpc-async": { "libraryClient": "VersionsAsyncClient", "rpcs": { + "CompareVersions": { + "methods": [ + "compare_versions" + ] + }, "CreateVersion": { "methods": [ "create_version" diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py index 427b543a..f5d02195 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3beta1.services.agents import pagers @@ -181,10 +183,10 @@ def __init__( async def list_agents( self, - request: agent.ListAgentsRequest = None, + request: Union[agent.ListAgentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListAgentsAsyncPager: @@ -192,7 +194,7 @@ async def list_agents( location. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListAgentsRequest, dict]): The request object. The request message for [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. parent (:class:`str`): @@ -262,17 +264,17 @@ async def list_agents( async def get_agent( self, - request: agent.GetAgentRequest = None, + request: Union[agent.GetAgentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.Agent: r"""Retrieves the specified agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetAgentRequest, dict]): The request object. The request message for [Agents.GetAgent][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgent]. name (:class:`str`): @@ -345,11 +347,11 @@ async def get_agent( async def create_agent( self, - request: gcdc_agent.CreateAgentRequest = None, + request: Union[gcdc_agent.CreateAgentRequest, dict] = None, *, parent: str = None, agent: gcdc_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_agent.Agent: @@ -360,7 +362,7 @@ async def create_agent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateAgentRequest, dict]): The request object. The request message for [Agents.CreateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.CreateAgent]. parent (:class:`str`): @@ -440,11 +442,11 @@ async def create_agent( async def update_agent( self, - request: gcdc_agent.UpdateAgentRequest = None, + request: Union[gcdc_agent.UpdateAgentRequest, dict] = None, *, agent: gcdc_agent.Agent = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_agent.Agent: @@ -455,7 +457,7 @@ async def update_agent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateAgentRequest, dict]): The request object. The request message for [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent]. agent (:class:`google.cloud.dialogflowcx_v3beta1.types.Agent`): @@ -538,17 +540,17 @@ async def update_agent( async def delete_agent( self, - request: agent.DeleteAgentRequest = None, + request: Union[agent.DeleteAgentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteAgentRequest, dict]): The request object. The request message for [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3beta1.Agents.DeleteAgent]. name (:class:`str`): @@ -602,9 +604,9 @@ async def delete_agent( async def export_agent( self, - request: agent.ExportAgentRequest = None, + request: Union[agent.ExportAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -621,7 +623,7 @@ async def export_agent( [ExportAgentResponse][google.cloud.dialogflow.cx.v3beta1.ExportAgentResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ExportAgentRequest, dict]): The request object. The request message for [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -673,9 +675,9 @@ async def export_agent( async def restore_agent( self, - request: agent.RestoreAgentRequest = None, + request: Union[agent.RestoreAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -700,7 +702,7 @@ async def restore_agent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest, dict]): The request object. The request message for [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3beta1.Agents.RestoreAgent]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -761,9 +763,9 @@ async def restore_agent( async def validate_agent( self, - request: agent.ValidateAgentRequest = None, + request: Union[agent.ValidateAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.AgentValidationResult: @@ -773,7 +775,7 @@ async def validate_agent( completed to get the complete validation results. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ValidateAgentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ValidateAgentRequest, dict]): The request object. The request message for [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ValidateAgent]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -813,10 +815,10 @@ async def validate_agent( async def get_agent_validation_result( self, - request: agent.GetAgentValidationResultRequest = None, + request: Union[agent.GetAgentValidationResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.AgentValidationResult: @@ -824,7 +826,7 @@ async def get_agent_validation_result( validation is performed when ValidateAgent is called. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetAgentValidationResultRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetAgentValidationResultRequest, dict]): The request object. The request message for [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/client.py b/google/cloud/dialogflowcx_v3beta1/services/agents/client.py index a30e5416..59a17327 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3beta1.services.agents import pagers @@ -446,7 +448,7 @@ def list_agents( request: Union[agent.ListAgentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListAgentsPager: @@ -527,7 +529,7 @@ def get_agent( request: Union[agent.GetAgentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.Agent: @@ -611,7 +613,7 @@ def create_agent( *, parent: str = None, agent: gcdc_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_agent.Agent: @@ -706,7 +708,7 @@ def update_agent( *, agent: gcdc_agent.Agent = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_agent.Agent: @@ -803,7 +805,7 @@ def delete_agent( request: Union[agent.DeleteAgentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -866,7 +868,7 @@ def export_agent( self, request: Union[agent.ExportAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -938,7 +940,7 @@ def restore_agent( self, request: Union[agent.RestoreAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1027,7 +1029,7 @@ def validate_agent( self, request: Union[agent.ValidateAgentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.AgentValidationResult: @@ -1081,7 +1083,7 @@ def get_agent_validation_result( request: Union[agent.GetAgentValidationResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> agent.AgentValidationResult: diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py index b7c268dd..49514f95 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 AgentsTransport(abc.ABC): """Abstract transport class for Agents.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { @@ -202,7 +169,7 @@ def close(self): raise NotImplementedError() @property - def operations_client(self) -> operations_v1.OperationsClient: + def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py index 227a5933..69ce80f5 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py @@ -115,7 +115,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) 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 b6abb12d..83c4af30 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py @@ -21,7 +21,6 @@ from google.api_core import operations_v1 # 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 @@ -162,7 +161,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3beta1/services/changelogs/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/changelogs/__init__.py new file mode 100644 index 00000000..028672a9 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/changelogs/__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 ChangelogsClient +from .async_client import ChangelogsAsyncClient + +__all__ = ( + "ChangelogsClient", + "ChangelogsAsyncClient", +) diff --git a/google/cloud/dialogflowcx_v3beta1/services/changelogs/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/changelogs/async_client.py new file mode 100644 index 00000000..87b046e3 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/changelogs/async_client.py @@ -0,0 +1,331 @@ +# -*- 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 + +from google.api_core.client_options import 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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.dialogflowcx_v3beta1.services.changelogs import pagers +from google.cloud.dialogflowcx_v3beta1.types import changelog +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ChangelogsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ChangelogsGrpcAsyncIOTransport +from .client import ChangelogsClient + + +class ChangelogsAsyncClient: + """Service for managing + [Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog]. + """ + + _client: ChangelogsClient + + DEFAULT_ENDPOINT = ChangelogsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ChangelogsClient.DEFAULT_MTLS_ENDPOINT + + changelog_path = staticmethod(ChangelogsClient.changelog_path) + parse_changelog_path = staticmethod(ChangelogsClient.parse_changelog_path) + common_billing_account_path = staticmethod( + ChangelogsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ChangelogsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(ChangelogsClient.common_folder_path) + parse_common_folder_path = staticmethod(ChangelogsClient.parse_common_folder_path) + common_organization_path = staticmethod(ChangelogsClient.common_organization_path) + parse_common_organization_path = staticmethod( + ChangelogsClient.parse_common_organization_path + ) + common_project_path = staticmethod(ChangelogsClient.common_project_path) + parse_common_project_path = staticmethod(ChangelogsClient.parse_common_project_path) + common_location_path = staticmethod(ChangelogsClient.common_location_path) + parse_common_location_path = staticmethod( + ChangelogsClient.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: + ChangelogsAsyncClient: The constructed client. + """ + return ChangelogsClient.from_service_account_info.__func__(ChangelogsAsyncClient, 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: + ChangelogsAsyncClient: The constructed client. + """ + return ChangelogsClient.from_service_account_file.__func__(ChangelogsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ChangelogsTransport: + """Returns the transport used by the client instance. + + Returns: + ChangelogsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(ChangelogsClient).get_transport_class, type(ChangelogsClient) + ) + + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ChangelogsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the changelogs 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, ~.ChangelogsTransport]): 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 = ChangelogsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_changelogs( + self, + request: Union[changelog.ListChangelogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListChangelogsAsyncPager: + r"""Returns the list of Changelogs. + + Args: + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListChangelogsRequest, dict]): + The request object. The request message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3beta1.Changelogs.ListChangelogs]. + parent (:class:`str`): + Required. The agent containing the changelogs. Format: + ``projects//locations//agents/``. + + 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.changelogs.pagers.ListChangelogsAsyncPager: + The response message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3beta1.Changelogs.ListChangelogs]. + + 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 = changelog.ListChangelogsRequest(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_changelogs, + 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.ListChangelogsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_changelog( + self, + request: Union[changelog.GetChangelogRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> changelog.Changelog: + r"""Retrieves the specified Changelog. + + Args: + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetChangelogRequest, dict]): + The request object. The request message for + [Changelogs.GetChangelog][google.cloud.dialogflow.cx.v3beta1.Changelogs.GetChangelog]. + name (:class:`str`): + Required. The name of the changelog to get. Format: + ``projects//locations//agents//changelogs/``. + + 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.Changelog: + Changelogs represents a change made + to a given agent. + + """ + # 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 = changelog.GetChangelogRequest(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_changelog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +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__ = ("ChangelogsAsyncClient",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/changelogs/client.py b/google/cloud/dialogflowcx_v3beta1/services/changelogs/client.py new file mode 100644 index 00000000..0017d825 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/changelogs/client.py @@ -0,0 +1,528 @@ +# -*- 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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.dialogflowcx_v3beta1.services.changelogs import pagers +from google.cloud.dialogflowcx_v3beta1.types import changelog +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ChangelogsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ChangelogsGrpcTransport +from .transports.grpc_asyncio import ChangelogsGrpcAsyncIOTransport + + +class ChangelogsClientMeta(type): + """Metaclass for the Changelogs 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[ChangelogsTransport]] + _transport_registry["grpc"] = ChangelogsGrpcTransport + _transport_registry["grpc_asyncio"] = ChangelogsGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ChangelogsTransport]: + """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 ChangelogsClient(metaclass=ChangelogsClientMeta): + """Service for managing + [Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog]. + """ + + @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: + ChangelogsClient: 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: + ChangelogsClient: 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) -> ChangelogsTransport: + """Returns the transport used by the client instance. + + Returns: + ChangelogsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def changelog_path(project: str, location: str, agent: str, changelog: str,) -> str: + """Returns a fully-qualified changelog string.""" + return "projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}".format( + project=project, location=location, agent=agent, changelog=changelog, + ) + + @staticmethod + def parse_changelog_path(path: str) -> Dict[str, str]: + """Parses a changelog path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/changelogs/(?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, ChangelogsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the changelogs 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, ChangelogsTransport]): 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, ChangelogsTransport): + # transport is a ChangelogsTransport 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=True, + ) + + def list_changelogs( + self, + request: Union[changelog.ListChangelogsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListChangelogsPager: + r"""Returns the list of Changelogs. + + Args: + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListChangelogsRequest, dict]): + The request object. The request message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3beta1.Changelogs.ListChangelogs]. + parent (str): + Required. The agent containing the changelogs. Format: + ``projects//locations//agents/``. + + 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.changelogs.pagers.ListChangelogsPager: + The response message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3beta1.Changelogs.ListChangelogs]. + + 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 changelog.ListChangelogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, changelog.ListChangelogsRequest): + request = changelog.ListChangelogsRequest(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_changelogs] + + # 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.ListChangelogsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_changelog( + self, + request: Union[changelog.GetChangelogRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> changelog.Changelog: + r"""Retrieves the specified Changelog. + + Args: + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetChangelogRequest, dict]): + The request object. The request message for + [Changelogs.GetChangelog][google.cloud.dialogflow.cx.v3beta1.Changelogs.GetChangelog]. + name (str): + Required. The name of the changelog to get. Format: + ``projects//locations//agents//changelogs/``. + + 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.Changelog: + Changelogs represents a change made + to a given agent. + + """ + # 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 changelog.GetChangelogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, changelog.GetChangelogRequest): + request = changelog.GetChangelogRequest(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_changelog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +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__ = ("ChangelogsClient",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/changelogs/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/changelogs/pagers.py new file mode 100644 index 00000000..98c43848 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/changelogs/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, + AsyncIterator, + Awaitable, + Callable, + Sequence, + Tuple, + Optional, + Iterator, +) + +from google.cloud.dialogflowcx_v3beta1.types import changelog + + +class ListChangelogsPager: + """A pager for iterating through ``list_changelogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListChangelogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``changelogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListChangelogs`` requests and continue to iterate + through the ``changelogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListChangelogsResponse` + 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[..., changelog.ListChangelogsResponse], + request: changelog.ListChangelogsRequest, + response: changelog.ListChangelogsResponse, + *, + 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.ListChangelogsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListChangelogsResponse): + 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 = changelog.ListChangelogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[changelog.ListChangelogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[changelog.Changelog]: + for page in self.pages: + yield from page.changelogs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListChangelogsAsyncPager: + """A pager for iterating through ``list_changelogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListChangelogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``changelogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListChangelogs`` requests and continue to iterate + through the ``changelogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListChangelogsResponse` + 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[changelog.ListChangelogsResponse]], + request: changelog.ListChangelogsRequest, + response: changelog.ListChangelogsResponse, + *, + 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.ListChangelogsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListChangelogsResponse): + 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 = changelog.ListChangelogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[changelog.ListChangelogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[changelog.Changelog]: + async def async_generator(): + async for page in self.pages: + for response in page.changelogs: + 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/changelogs/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/__init__.py new file mode 100644 index 00000000..882554f3 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/changelogs/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 ChangelogsTransport +from .grpc import ChangelogsGrpcTransport +from .grpc_asyncio import ChangelogsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ChangelogsTransport]] +_transport_registry["grpc"] = ChangelogsGrpcTransport +_transport_registry["grpc_asyncio"] = ChangelogsGrpcAsyncIOTransport + +__all__ = ( + "ChangelogsTransport", + "ChangelogsGrpcTransport", + "ChangelogsGrpcAsyncIOTransport", +) diff --git a/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/base.py new file mode 100644 index 00000000..8fc3ae96 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/base.py @@ -0,0 +1,166 @@ +# -*- 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 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 changelog + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ChangelogsTransport(abc.ABC): + """Abstract transport class for Changelogs.""" + + 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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + + # 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_changelogs: gapic_v1.method.wrap_method( + self.list_changelogs, default_timeout=None, client_info=client_info, + ), + self.get_changelog: gapic_v1.method.wrap_method( + self.get_changelog, default_timeout=None, client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_changelogs( + self, + ) -> Callable[ + [changelog.ListChangelogsRequest], + Union[ + changelog.ListChangelogsResponse, + Awaitable[changelog.ListChangelogsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_changelog( + self, + ) -> Callable[ + [changelog.GetChangelogRequest], + Union[changelog.Changelog, Awaitable[changelog.Changelog]], + ]: + raise NotImplementedError() + + +__all__ = ("ChangelogsTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc.py new file mode 100644 index 00000000..2469dac8 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc.py @@ -0,0 +1,285 @@ +# -*- 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 changelog +from .base import ChangelogsTransport, DEFAULT_CLIENT_INFO + + +class ChangelogsGrpcTransport(ChangelogsTransport): + """gRPC backend transport for Changelogs. + + Service for managing + [Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog]. + + 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_changelogs( + self, + ) -> Callable[[changelog.ListChangelogsRequest], changelog.ListChangelogsResponse]: + r"""Return a callable for the list changelogs method over gRPC. + + Returns the list of Changelogs. + + Returns: + Callable[[~.ListChangelogsRequest], + ~.ListChangelogsResponse]: + 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_changelogs" not in self._stubs: + self._stubs["list_changelogs"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Changelogs/ListChangelogs", + request_serializer=changelog.ListChangelogsRequest.serialize, + response_deserializer=changelog.ListChangelogsResponse.deserialize, + ) + return self._stubs["list_changelogs"] + + @property + def get_changelog( + self, + ) -> Callable[[changelog.GetChangelogRequest], changelog.Changelog]: + r"""Return a callable for the get changelog method over gRPC. + + Retrieves the specified Changelog. + + Returns: + Callable[[~.GetChangelogRequest], + ~.Changelog]: + 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_changelog" not in self._stubs: + self._stubs["get_changelog"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Changelogs/GetChangelog", + request_serializer=changelog.GetChangelogRequest.serialize, + response_deserializer=changelog.Changelog.deserialize, + ) + return self._stubs["get_changelog"] + + def close(self): + self.grpc_channel.close() + + +__all__ = ("ChangelogsGrpcTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc_asyncio.py new file mode 100644 index 00000000..9b746711 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc_asyncio.py @@ -0,0 +1,289 @@ +# -*- 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 grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import changelog +from .base import ChangelogsTransport, DEFAULT_CLIENT_INFO +from .grpc import ChangelogsGrpcTransport + + +class ChangelogsGrpcAsyncIOTransport(ChangelogsTransport): + """gRPC AsyncIO backend transport for Changelogs. + + Service for managing + [Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog]. + + 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_changelogs( + self, + ) -> Callable[ + [changelog.ListChangelogsRequest], Awaitable[changelog.ListChangelogsResponse] + ]: + r"""Return a callable for the list changelogs method over gRPC. + + Returns the list of Changelogs. + + Returns: + Callable[[~.ListChangelogsRequest], + Awaitable[~.ListChangelogsResponse]]: + 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_changelogs" not in self._stubs: + self._stubs["list_changelogs"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Changelogs/ListChangelogs", + request_serializer=changelog.ListChangelogsRequest.serialize, + response_deserializer=changelog.ListChangelogsResponse.deserialize, + ) + return self._stubs["list_changelogs"] + + @property + def get_changelog( + self, + ) -> Callable[[changelog.GetChangelogRequest], Awaitable[changelog.Changelog]]: + r"""Return a callable for the get changelog method over gRPC. + + Retrieves the specified Changelog. + + Returns: + Callable[[~.GetChangelogRequest], + Awaitable[~.Changelog]]: + 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_changelog" not in self._stubs: + self._stubs["get_changelog"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Changelogs/GetChangelog", + request_serializer=changelog.GetChangelogRequest.serialize, + response_deserializer=changelog.Changelog.deserialize, + ) + return self._stubs["get_changelog"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("ChangelogsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py index ad1f98d6..299f4d8d 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + 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 @@ -170,10 +172,10 @@ def __init__( async def list_deployments( self, - request: deployment.ListDeploymentsRequest = None, + request: Union[deployment.ListDeploymentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListDeploymentsAsyncPager: @@ -181,7 +183,7 @@ async def list_deployments( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsRequest`): + 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 (:class:`str`): @@ -253,10 +255,10 @@ async def list_deployments( async def get_deployment( self, - request: deployment.GetDeploymentRequest = None, + request: Union[deployment.GetDeploymentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> deployment.Deployment: @@ -264,7 +266,7 @@ async def get_deployment( [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetDeploymentRequest`): + 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 (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py index d8d7731b..642985a2 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + 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 @@ -421,7 +423,7 @@ def list_deployments( request: Union[deployment.ListDeploymentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListDeploymentsPager: @@ -504,7 +506,7 @@ def get_deployment( request: Union[deployment.GetDeploymentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> deployment.Deployment: diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py index 8e85c9e5..153689d0 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -37,15 +36,6 @@ 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.""" @@ -98,7 +88,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -131,29 +121,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py index ce13bbf5..7753f3aa 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py index b7bd321d..e5c8dbf5 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.entity_types import pagers from google.cloud.dialogflowcx_v3beta1.types import entity_type from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type @@ -163,10 +165,10 @@ def __init__( async def list_entity_types( self, - request: entity_type.ListEntityTypesRequest = None, + request: Union[entity_type.ListEntityTypesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEntityTypesAsyncPager: @@ -174,7 +176,7 @@ async def list_entity_types( agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListEntityTypesRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListEntityTypesRequest, dict]): The request object. The request message for [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.EntityTypes.ListEntityTypes]. parent (:class:`str`): @@ -245,17 +247,17 @@ async def list_entity_types( async def get_entity_type( self, - request: entity_type.GetEntityTypeRequest = None, + request: Union[entity_type.GetEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> entity_type.EntityType: r"""Retrieves the specified entity type. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetEntityTypeRequest, dict]): The request object. The request message for [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.GetEntityType]. name (:class:`str`): @@ -348,18 +350,18 @@ async def get_entity_type( async def create_entity_type( self, - request: gcdc_entity_type.CreateEntityTypeRequest = None, + request: Union[gcdc_entity_type.CreateEntityTypeRequest, dict] = None, *, parent: str = None, entity_type: gcdc_entity_type.EntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_entity_type.EntityType: r"""Creates an entity type in the specified agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateEntityTypeRequest, dict]): The request object. The request message for [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.CreateEntityType]. parent (:class:`str`): @@ -459,11 +461,11 @@ async def create_entity_type( async def update_entity_type( self, - request: gcdc_entity_type.UpdateEntityTypeRequest = None, + request: Union[gcdc_entity_type.UpdateEntityTypeRequest, dict] = None, *, entity_type: gcdc_entity_type.EntityType = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_entity_type.EntityType: @@ -474,7 +476,7 @@ async def update_entity_type( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateEntityTypeRequest, dict]): The request object. The request message for [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.UpdateEntityType]. entity_type (:class:`google.cloud.dialogflowcx_v3beta1.types.EntityType`): @@ -576,10 +578,10 @@ async def update_entity_type( async def delete_entity_type( self, - request: entity_type.DeleteEntityTypeRequest = None, + request: Union[entity_type.DeleteEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -590,7 +592,7 @@ async def delete_entity_type( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteEntityTypeRequest, dict]): The request object. The request message for [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.DeleteEntityType]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py b/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py index 3d6e7f23..2879baf3 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.entity_types import pagers from google.cloud.dialogflowcx_v3beta1.types import entity_type from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type @@ -356,7 +358,7 @@ def list_entity_types( request: Union[entity_type.ListEntityTypesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEntityTypesPager: @@ -438,7 +440,7 @@ def get_entity_type( request: Union[entity_type.GetEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> entity_type.EntityType: @@ -542,7 +544,7 @@ def create_entity_type( *, parent: str = None, entity_type: gcdc_entity_type.EntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_entity_type.EntityType: @@ -653,7 +655,7 @@ def update_entity_type( *, entity_type: gcdc_entity_type.EntityType = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_entity_type.EntityType: @@ -769,7 +771,7 @@ def delete_entity_type( request: Union[entity_type.DeleteEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py index 35a7ac2a..1a9bd64b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -39,15 +38,6 @@ 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 EntityTypesTransport(abc.ABC): """Abstract transport class for EntityTypes.""" @@ -100,7 +90,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -133,29 +123,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py index ed9cb767..91127bf7 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py index 2455f34e..2b205745 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3beta1.services.environments import pagers @@ -181,10 +183,10 @@ def __init__( async def list_environments( self, - request: environment.ListEnvironmentsRequest = None, + request: Union[environment.ListEnvironmentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEnvironmentsAsyncPager: @@ -192,7 +194,7 @@ async def list_environments( [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListEnvironmentsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListEnvironmentsRequest, dict]): The request object. The request message for [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.Environments.ListEnvironments]. parent (:class:`str`): @@ -264,10 +266,10 @@ async def list_environments( async def get_environment( self, - request: environment.GetEnvironmentRequest = None, + request: Union[environment.GetEnvironmentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> environment.Environment: @@ -275,7 +277,7 @@ async def get_environment( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetEnvironmentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetEnvironmentRequest, dict]): The request object. The request message for [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.GetEnvironment]. name (:class:`str`): @@ -351,11 +353,11 @@ async def get_environment( async def create_environment( self, - request: gcdc_environment.CreateEnvironmentRequest = None, + request: Union[gcdc_environment.CreateEnvironmentRequest, dict] = None, *, parent: str = None, environment: gcdc_environment.Environment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -374,7 +376,7 @@ async def create_environment( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateEnvironmentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateEnvironmentRequest, dict]): The request object. The request message for [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.CreateEnvironment]. parent (:class:`str`): @@ -465,11 +467,11 @@ async def create_environment( async def update_environment( self, - request: gcdc_environment.UpdateEnvironmentRequest = None, + request: Union[gcdc_environment.UpdateEnvironmentRequest, dict] = None, *, environment: gcdc_environment.Environment = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -487,7 +489,7 @@ async def update_environment( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateEnvironmentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateEnvironmentRequest, dict]): The request object. The request message for [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.UpdateEnvironment]. environment (:class:`google.cloud.dialogflowcx_v3beta1.types.Environment`): @@ -576,10 +578,10 @@ async def update_environment( async def delete_environment( self, - request: environment.DeleteEnvironmentRequest = None, + request: Union[environment.DeleteEnvironmentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -587,7 +589,7 @@ async def delete_environment( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteEnvironmentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteEnvironmentRequest, dict]): The request object. The request message for [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.DeleteEnvironment]. name (:class:`str`): @@ -643,10 +645,10 @@ async def delete_environment( async def lookup_environment_history( self, - request: environment.LookupEnvironmentHistoryRequest = None, + request: Union[environment.LookupEnvironmentHistoryRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.LookupEnvironmentHistoryAsyncPager: @@ -654,7 +656,7 @@ async def lookup_environment_history( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryRequest, dict]): The request object. The request message for [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. name (:class:`str`): @@ -725,9 +727,9 @@ async def lookup_environment_history( async def run_continuous_test( self, - request: environment.RunContinuousTestRequest = None, + request: Union[environment.RunContinuousTestRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -745,7 +747,7 @@ async def run_continuous_test( [RunContinuousTestResponse][google.cloud.dialogflow.cx.v3beta1.RunContinuousTestResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestRequest, dict]): The request object. The request message for [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -799,10 +801,10 @@ async def run_continuous_test( async def list_continuous_test_results( self, - request: environment.ListContinuousTestResultsRequest = None, + request: Union[environment.ListContinuousTestResultsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListContinuousTestResultsAsyncPager: @@ -810,7 +812,7 @@ async def list_continuous_test_results( environment. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest, dict]): The request object. The request message for [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3beta1.Environments.ListContinuousTestResults]. parent (:class:`str`): @@ -880,9 +882,9 @@ async def list_continuous_test_results( async def deploy_flow( self, - request: environment.DeployFlowRequest = None, + request: Union[environment.DeployFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -900,7 +902,7 @@ async def deploy_flow( [DeployFlowResponse][google.cloud.dialogflow.cx.v3beta1.DeployFlowResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeployFlowRequest`): + 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, diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/client.py b/google/cloud/dialogflowcx_v3beta1/services/environments/client.py index 505beb11..be67d9ac 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3beta1.services.environments import pagers @@ -442,7 +444,7 @@ def list_environments( request: Union[environment.ListEnvironmentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEnvironmentsPager: @@ -525,7 +527,7 @@ def get_environment( request: Union[environment.GetEnvironmentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> environment.Environment: @@ -613,7 +615,7 @@ def create_environment( *, parent: str = None, environment: gcdc_environment.Environment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -727,7 +729,7 @@ def update_environment( *, environment: gcdc_environment.Environment = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -837,7 +839,7 @@ def delete_environment( request: Union[environment.DeleteEnvironmentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -904,7 +906,7 @@ def lookup_environment_history( request: Union[environment.LookupEnvironmentHistoryRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.LookupEnvironmentHistoryPager: @@ -987,7 +989,7 @@ def run_continuous_test( self, request: Union[environment.RunContinuousTestRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1063,7 +1065,7 @@ def list_continuous_test_results( request: Union[environment.ListContinuousTestResultsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListContinuousTestResultsPager: @@ -1145,7 +1147,7 @@ def deploy_flow( self, request: Union[environment.DeployFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py index 73675961..3ff2a21d 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 EnvironmentsTransport(abc.ABC): """Abstract transport class for Environments.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { @@ -204,7 +171,7 @@ def close(self): raise NotImplementedError() @property - def operations_client(self) -> operations_v1.OperationsClient: + def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py index 18b8341f..925cab53 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py @@ -115,7 +115,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) 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 0dd06185..519e60f2 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py @@ -21,7 +21,6 @@ from google.api_core import operations_v1 # 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 @@ -162,7 +161,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py index 312de8f5..c53b7b5c 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.experiments import pagers from google.cloud.dialogflowcx_v3beta1.types import experiment from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment @@ -167,10 +169,10 @@ def __init__( async def list_experiments( self, - request: experiment.ListExperimentsRequest = None, + request: Union[experiment.ListExperimentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListExperimentsAsyncPager: @@ -178,7 +180,7 @@ async def list_experiments( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListExperimentsRequest, dict]): The request object. The request message for [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. parent (:class:`str`): @@ -250,10 +252,10 @@ async def list_experiments( async def get_experiment( self, - request: experiment.GetExperimentRequest = None, + request: Union[experiment.GetExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: @@ -261,7 +263,7 @@ async def get_experiment( [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetExperimentRequest, dict]): The request object. The request message for [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.GetExperiment]. name (:class:`str`): @@ -324,11 +326,11 @@ async def get_experiment( async def create_experiment( self, - request: gcdc_experiment.CreateExperimentRequest = None, + request: Union[gcdc_experiment.CreateExperimentRequest, dict] = None, *, parent: str = None, experiment: gcdc_experiment.Experiment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_experiment.Experiment: @@ -338,7 +340,7 @@ async def create_experiment( [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateExperimentRequest, dict]): The request object. The request message for [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.CreateExperiment]. parent (:class:`str`): @@ -410,11 +412,11 @@ async def create_experiment( async def update_experiment( self, - request: gcdc_experiment.UpdateExperimentRequest = None, + request: Union[gcdc_experiment.UpdateExperimentRequest, dict] = None, *, experiment: gcdc_experiment.Experiment = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_experiment.Experiment: @@ -422,7 +424,7 @@ async def update_experiment( [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateExperimentRequest, dict]): The request object. The request message for [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.UpdateExperiment]. experiment (:class:`google.cloud.dialogflowcx_v3beta1.types.Experiment`): @@ -492,10 +494,10 @@ async def update_experiment( async def delete_experiment( self, - request: experiment.DeleteExperimentRequest = None, + request: Union[experiment.DeleteExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -503,7 +505,7 @@ async def delete_experiment( [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteExperimentRequest, dict]): The request object. The request message for [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.DeleteExperiment]. name (:class:`str`): @@ -559,10 +561,10 @@ async def delete_experiment( async def start_experiment( self, - request: experiment.StartExperimentRequest = None, + request: Union[experiment.StartExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: @@ -572,7 +574,7 @@ async def start_experiment( RUNNING. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.StartExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.StartExperimentRequest, dict]): The request object. The request message for [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StartExperiment]. name (:class:`str`): @@ -634,10 +636,10 @@ async def start_experiment( async def stop_experiment( self, - request: experiment.StopExperimentRequest = None, + request: Union[experiment.StopExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: @@ -647,7 +649,7 @@ async def stop_experiment( DONE. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.StopExperimentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.StopExperimentRequest, dict]): The request object. The request message for [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StopExperiment]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py index e8c1e5cd..b6291bd1 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.experiments import pagers from google.cloud.dialogflowcx_v3beta1.types import experiment from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment @@ -380,7 +382,7 @@ def list_experiments( request: Union[experiment.ListExperimentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListExperimentsPager: @@ -463,7 +465,7 @@ def get_experiment( request: Union[experiment.GetExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: @@ -538,7 +540,7 @@ def create_experiment( *, parent: str = None, experiment: gcdc_experiment.Experiment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_experiment.Experiment: @@ -624,7 +626,7 @@ def update_experiment( *, experiment: gcdc_experiment.Experiment = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_experiment.Experiment: @@ -705,7 +707,7 @@ def delete_experiment( request: Union[experiment.DeleteExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -772,7 +774,7 @@ def start_experiment( request: Union[experiment.StartExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: @@ -847,7 +849,7 @@ def stop_experiment( request: Union[experiment.StopExperimentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> experiment.Experiment: diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py index 2c89a6d9..33d34e73 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -39,15 +38,6 @@ 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 ExperimentsTransport(abc.ABC): """Abstract transport class for Experiments.""" @@ -100,7 +90,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -133,29 +123,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py index 14a95c7f..ff9faffa 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py index c5da4ce2..acdbbe22 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3beta1.services.flows import pagers @@ -178,11 +180,11 @@ def __init__( async def create_flow( self, - request: gcdc_flow.CreateFlowRequest = None, + request: Union[gcdc_flow.CreateFlowRequest, dict] = None, *, parent: str = None, flow: gcdc_flow.Flow = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_flow.Flow: @@ -193,7 +195,7 @@ async def create_flow( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateFlowRequest, dict]): The request object. The request message for [Flows.CreateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.CreateFlow]. parent (:class:`str`): @@ -282,17 +284,17 @@ async def create_flow( async def delete_flow( self, - request: flow.DeleteFlowRequest = None, + request: Union[flow.DeleteFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes a specified flow. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteFlowRequest, dict]): The request object. The request message for [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3beta1.Flows.DeleteFlow]. name (:class:`str`): @@ -346,17 +348,17 @@ async def delete_flow( async def list_flows( self, - request: flow.ListFlowsRequest = None, + request: Union[flow.ListFlowsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListFlowsAsyncPager: r"""Returns the list of all flows in the specified agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListFlowsRequest, dict]): The request object. The request message for [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. parent (:class:`str`): @@ -426,17 +428,17 @@ async def list_flows( async def get_flow( self, - request: flow.GetFlowRequest = None, + request: Union[flow.GetFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.Flow: r"""Retrieves the specified flow. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetFlowRequest, dict]): The request object. The response message for [Flows.GetFlow][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlow]. name (:class:`str`): @@ -518,11 +520,11 @@ async def get_flow( async def update_flow( self, - request: gcdc_flow.UpdateFlowRequest = None, + request: Union[gcdc_flow.UpdateFlowRequest, dict] = None, *, flow: gcdc_flow.Flow = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_flow.Flow: @@ -533,7 +535,7 @@ async def update_flow( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateFlowRequest, dict]): The request object. The request message for [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.UpdateFlow]. flow (:class:`google.cloud.dialogflowcx_v3beta1.types.Flow`): @@ -625,10 +627,10 @@ async def update_flow( async def train_flow( self, - request: flow.TrainFlowRequest = None, + request: Union[flow.TrainFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -650,7 +652,7 @@ async def train_flow( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.TrainFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.TrainFlowRequest, dict]): The request object. The request message for [Flows.TrainFlow][google.cloud.dialogflow.cx.v3beta1.Flows.TrainFlow]. name (:class:`str`): @@ -732,9 +734,9 @@ async def train_flow( async def validate_flow( self, - request: flow.ValidateFlowRequest = None, + request: Union[flow.ValidateFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.FlowValidationResult: @@ -744,7 +746,7 @@ async def validate_flow( results. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ValidateFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ValidateFlowRequest, dict]): The request object. The request message for [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ValidateFlow]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -784,10 +786,10 @@ async def validate_flow( async def get_flow_validation_result( self, - request: flow.GetFlowValidationResultRequest = None, + request: Union[flow.GetFlowValidationResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.FlowValidationResult: @@ -795,7 +797,7 @@ async def get_flow_validation_result( validation is performed when ValidateFlow is called. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetFlowValidationResultRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetFlowValidationResultRequest, dict]): The request object. The request message for [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. name (:class:`str`): @@ -856,9 +858,9 @@ async def get_flow_validation_result( async def import_flow( self, - request: flow.ImportFlowRequest = None, + request: Union[flow.ImportFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -880,7 +882,7 @@ async def import_flow( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest, dict]): The request object. The request message for [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -932,9 +934,9 @@ async def import_flow( async def export_flow( self, - request: flow.ExportFlowRequest = None, + request: Union[flow.ExportFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -954,7 +956,7 @@ async def export_flow( flow references will also be exported. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ExportFlowRequest, dict]): The request object. The request message for [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. retry (google.api_core.retry.Retry): Designation of what errors, if any, diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/client.py b/google/cloud/dialogflowcx_v3beta1/services/flows/client.py index fd8aabdf..a9abbfb6 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3beta1.services.flows import pagers @@ -452,7 +454,7 @@ def create_flow( *, parent: str = None, flow: gcdc_flow.Flow = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_flow.Flow: @@ -555,7 +557,7 @@ def delete_flow( request: Union[flow.DeleteFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -619,7 +621,7 @@ def list_flows( request: Union[flow.ListFlowsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListFlowsPager: @@ -699,7 +701,7 @@ def get_flow( request: Union[flow.GetFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.Flow: @@ -792,7 +794,7 @@ def update_flow( *, flow: gcdc_flow.Flow = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_flow.Flow: @@ -898,7 +900,7 @@ def train_flow( request: Union[flow.TrainFlowRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1004,7 +1006,7 @@ def validate_flow( self, request: Union[flow.ValidateFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.FlowValidationResult: @@ -1058,7 +1060,7 @@ def get_flow_validation_result( request: Union[flow.GetFlowValidationResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> flow.FlowValidationResult: @@ -1131,7 +1133,7 @@ def import_flow( self, request: Union[flow.ImportFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1208,7 +1210,7 @@ def export_flow( self, request: Union[flow.ExportFlowRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py index 5ae53c6c..bb5b83f8 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 FlowsTransport(abc.ABC): """Abstract transport class for Flows.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { @@ -205,7 +172,7 @@ def close(self): raise NotImplementedError() @property - def operations_client(self) -> operations_v1.OperationsClient: + def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py index a30139a4..65bafded 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py @@ -115,7 +115,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) 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 58b8146e..66f9591e 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py @@ -21,7 +21,6 @@ from google.api_core import operations_v1 # 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 @@ -162,7 +161,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py index f6610213..d69bebf2 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.intents import pagers from google.cloud.dialogflowcx_v3beta1.types import intent from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent @@ -161,10 +163,10 @@ def __init__( async def list_intents( self, - request: intent.ListIntentsRequest = None, + request: Union[intent.ListIntentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListIntentsAsyncPager: @@ -172,7 +174,7 @@ async def list_intents( agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListIntentsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListIntentsRequest, dict]): The request object. The request message for [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.Intents.ListIntents]. parent (:class:`str`): @@ -242,17 +244,17 @@ async def list_intents( async def get_intent( self, - request: intent.GetIntentRequest = None, + request: Union[intent.GetIntentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> intent.Intent: r"""Retrieves the specified intent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetIntentRequest, dict]): The request object. The request message for [Intents.GetIntent][google.cloud.dialogflow.cx.v3beta1.Intents.GetIntent]. name (:class:`str`): @@ -318,11 +320,11 @@ async def get_intent( async def create_intent( self, - request: gcdc_intent.CreateIntentRequest = None, + request: Union[gcdc_intent.CreateIntentRequest, dict] = None, *, parent: str = None, intent: gcdc_intent.Intent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_intent.Intent: @@ -333,7 +335,7 @@ async def create_intent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateIntentRequest, dict]): The request object. The request message for [Intents.CreateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.CreateIntent]. parent (:class:`str`): @@ -406,11 +408,11 @@ async def create_intent( async def update_intent( self, - request: gcdc_intent.UpdateIntentRequest = None, + request: Union[gcdc_intent.UpdateIntentRequest, dict] = None, *, intent: gcdc_intent.Intent = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_intent.Intent: @@ -421,7 +423,7 @@ async def update_intent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateIntentRequest, dict]): The request object. The request message for [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.UpdateIntent]. intent (:class:`google.cloud.dialogflowcx_v3beta1.types.Intent`): @@ -497,10 +499,10 @@ async def update_intent( async def delete_intent( self, - request: intent.DeleteIntentRequest = None, + request: Union[intent.DeleteIntentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -511,7 +513,7 @@ async def delete_intent( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteIntentRequest, dict]): The request object. The request message for [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3beta1.Intents.DeleteIntent]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/client.py b/google/cloud/dialogflowcx_v3beta1/services/intents/client.py index 2e5864d8..6e593b3f 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.intents import pagers from google.cloud.dialogflowcx_v3beta1.types import intent from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent @@ -372,7 +374,7 @@ def list_intents( request: Union[intent.ListIntentsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListIntentsPager: @@ -453,7 +455,7 @@ def get_intent( request: Union[intent.GetIntentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> intent.Intent: @@ -530,7 +532,7 @@ def create_intent( *, parent: str = None, intent: gcdc_intent.Intent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_intent.Intent: @@ -618,7 +620,7 @@ def update_intent( *, intent: gcdc_intent.Intent = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_intent.Intent: @@ -708,7 +710,7 @@ def delete_intent( request: Union[intent.DeleteIntentRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py index c54f9bd2..6da21ff4 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -39,15 +38,6 @@ 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 IntentsTransport(abc.ABC): """Abstract transport class for Intents.""" @@ -100,7 +90,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -133,29 +123,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py index 90e4359b..ff5fafc5 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py index cd90209d..2574cf88 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.pages import pagers from google.cloud.dialogflowcx_v3beta1.types import fulfillment from google.cloud.dialogflowcx_v3beta1.types import page @@ -170,17 +172,17 @@ def __init__( async def list_pages( self, - request: page.ListPagesRequest = None, + request: Union[page.ListPagesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListPagesAsyncPager: r"""Returns the list of all pages in the specified flow. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListPagesRequest, dict]): The request object. The request message for [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. parent (:class:`str`): @@ -250,17 +252,17 @@ async def list_pages( async def get_page( self, - request: page.GetPageRequest = None, + request: Union[page.GetPageRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> page.Page: r"""Retrieves the specified page. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetPageRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetPageRequest, dict]): The request object. The request message for [Pages.GetPage][google.cloud.dialogflow.cx.v3beta1.Pages.GetPage]. name (:class:`str`): @@ -341,18 +343,18 @@ async def get_page( async def create_page( self, - request: gcdc_page.CreatePageRequest = None, + request: Union[gcdc_page.CreatePageRequest, dict] = None, *, parent: str = None, page: gcdc_page.Page = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_page.Page: r"""Creates a page in the specified flow. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreatePageRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreatePageRequest, dict]): The request object. The request message for [Pages.CreatePage][google.cloud.dialogflow.cx.v3beta1.Pages.CreatePage]. parent (:class:`str`): @@ -440,18 +442,18 @@ async def create_page( async def update_page( self, - request: gcdc_page.UpdatePageRequest = None, + request: Union[gcdc_page.UpdatePageRequest, dict] = None, *, page: gcdc_page.Page = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_page.Page: r"""Updates the specified page. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdatePageRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdatePageRequest, dict]): The request object. The request message for [Pages.UpdatePage][google.cloud.dialogflow.cx.v3beta1.Pages.UpdatePage]. page (:class:`google.cloud.dialogflowcx_v3beta1.types.Page`): @@ -542,17 +544,17 @@ async def update_page( async def delete_page( self, - request: page.DeletePageRequest = None, + request: Union[page.DeletePageRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified page. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeletePageRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeletePageRequest, dict]): The request object. The request message for [Pages.DeletePage][google.cloud.dialogflow.cx.v3beta1.Pages.DeletePage]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/client.py b/google/cloud/dialogflowcx_v3beta1/services/pages/client.py index 0a021168..82741a78 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.pages import pagers from google.cloud.dialogflowcx_v3beta1.types import fulfillment from google.cloud.dialogflowcx_v3beta1.types import page @@ -445,7 +447,7 @@ def list_pages( request: Union[page.ListPagesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListPagesPager: @@ -525,7 +527,7 @@ def get_page( request: Union[page.GetPageRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> page.Page: @@ -617,7 +619,7 @@ def create_page( *, parent: str = None, page: gcdc_page.Page = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_page.Page: @@ -716,7 +718,7 @@ def update_page( *, page: gcdc_page.Page = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_page.Page: @@ -817,7 +819,7 @@ def delete_page( request: Union[page.DeletePageRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py index 3f81ac45..35f3614c 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -39,15 +38,6 @@ 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 PagesTransport(abc.ABC): """Abstract transport class for Pages.""" @@ -100,7 +90,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -133,29 +123,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py index 8634b5f0..6548290e 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py index 49507951..a35e24ec 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import pagers from google.cloud.dialogflowcx_v3beta1.types import security_settings from google.cloud.dialogflowcx_v3beta1.types import ( @@ -188,18 +190,20 @@ def __init__( async def create_security_settings( self, - request: gcdc_security_settings.CreateSecuritySettingsRequest = None, + request: Union[ + gcdc_security_settings.CreateSecuritySettingsRequest, dict + ] = None, *, parent: str = None, security_settings: gcdc_security_settings.SecuritySettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_security_settings.SecuritySettings: r"""Create security settings in the specified location. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateSecuritySettingsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateSecuritySettingsRequest, dict]): The request object. The request message for [SecuritySettings.CreateSecuritySettings][]. parent (:class:`str`): @@ -275,10 +279,10 @@ async def create_security_settings( async def get_security_settings( self, - request: security_settings.GetSecuritySettingsRequest = None, + request: Union[security_settings.GetSecuritySettingsRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> security_settings.SecuritySettings: @@ -287,7 +291,7 @@ async def get_security_settings( The returned settings may be stale by up to 1 minute. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetSecuritySettingsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetSecuritySettingsRequest, dict]): The request object. The request message for [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.GetSecuritySettings]. name (:class:`str`): @@ -352,11 +356,13 @@ async def get_security_settings( async def update_security_settings( self, - request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, + request: Union[ + gcdc_security_settings.UpdateSecuritySettingsRequest, dict + ] = None, *, security_settings: gcdc_security_settings.SecuritySettings = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_security_settings.SecuritySettings: @@ -364,7 +370,7 @@ async def update_security_settings( [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateSecuritySettingsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateSecuritySettingsRequest, dict]): The request object. The request message for [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings]. security_settings (:class:`google.cloud.dialogflowcx_v3beta1.types.SecuritySettings`): @@ -441,10 +447,10 @@ async def update_security_settings( async def list_security_settings( self, - request: security_settings.ListSecuritySettingsRequest = None, + request: Union[security_settings.ListSecuritySettingsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSecuritySettingsAsyncPager: @@ -452,7 +458,7 @@ async def list_security_settings( specified location. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsRequest, dict]): The request object. The request message for [SecuritySettings.ListSecuritySettings][]. parent (:class:`str`): @@ -523,10 +529,10 @@ async def list_security_settings( async def delete_security_settings( self, - request: security_settings.DeleteSecuritySettingsRequest = None, + request: Union[security_settings.DeleteSecuritySettingsRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -534,7 +540,7 @@ async def delete_security_settings( [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteSecuritySettingsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteSecuritySettingsRequest, dict]): The request object. The request message for [SecuritySettings.DeleteSecuritySettings][]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py index e4c9337a..cf2457cc 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import pagers from google.cloud.dialogflowcx_v3beta1.types import security_settings from google.cloud.dialogflowcx_v3beta1.types import ( @@ -403,7 +405,7 @@ def create_security_settings( *, parent: str = None, security_settings: gcdc_security_settings.SecuritySettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_security_settings.SecuritySettings: @@ -491,7 +493,7 @@ def get_security_settings( request: Union[security_settings.GetSecuritySettingsRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> security_settings.SecuritySettings: @@ -571,7 +573,7 @@ def update_security_settings( *, security_settings: gcdc_security_settings.SecuritySettings = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_security_settings.SecuritySettings: @@ -661,7 +663,7 @@ def list_security_settings( request: Union[security_settings.ListSecuritySettingsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSecuritySettingsPager: @@ -743,7 +745,7 @@ def delete_security_settings( request: Union[security_settings.DeleteSecuritySettingsRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py index 51ca552c..80a65103 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 SecuritySettingsServiceTransport(abc.ABC): """Abstract transport class for SecuritySettingsService.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py index d26ae7c9..25ac9a64 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py index 869f0362..b44407b2 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import pagers from google.cloud.dialogflowcx_v3beta1.types import entity_type from google.cloud.dialogflowcx_v3beta1.types import session_entity_type @@ -175,10 +177,10 @@ def __init__( async def list_session_entity_types( self, - request: session_entity_type.ListSessionEntityTypesRequest = None, + request: Union[session_entity_type.ListSessionEntityTypesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSessionEntityTypesAsyncPager: @@ -186,7 +188,7 @@ async def list_session_entity_types( specified session. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest, dict]): The request object. The request message for [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.ListSessionEntityTypes]. parent (:class:`str`): @@ -261,17 +263,17 @@ async def list_session_entity_types( async def get_session_entity_type( self, - request: session_entity_type.GetSessionEntityTypeRequest = None, + request: Union[session_entity_type.GetSessionEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session_entity_type.SessionEntityType: r"""Retrieves the specified session entity type. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetSessionEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetSessionEntityTypeRequest, dict]): The request object. The request message for [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.GetSessionEntityType]. name (:class:`str`): @@ -351,18 +353,20 @@ async def get_session_entity_type( async def create_session_entity_type( self, - request: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, + request: Union[ + gcdc_session_entity_type.CreateSessionEntityTypeRequest, dict + ] = None, *, parent: str = None, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: r"""Creates a session entity type. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateSessionEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateSessionEntityTypeRequest, dict]): The request object. The request message for [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.CreateSessionEntityType]. parent (:class:`str`): @@ -452,18 +456,20 @@ async def create_session_entity_type( async def update_session_entity_type( self, - request: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, + request: Union[ + gcdc_session_entity_type.UpdateSessionEntityTypeRequest, dict + ] = None, *, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: r"""Updates the specified session entity type. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateSessionEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateSessionEntityTypeRequest, dict]): The request object. The request message for [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.UpdateSessionEntityType]. session_entity_type (:class:`google.cloud.dialogflowcx_v3beta1.types.SessionEntityType`): @@ -554,17 +560,17 @@ async def update_session_entity_type( async def delete_session_entity_type( self, - request: session_entity_type.DeleteSessionEntityTypeRequest = None, + request: Union[session_entity_type.DeleteSessionEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified session entity type. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteSessionEntityTypeRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteSessionEntityTypeRequest, dict]): The request object. The request message for [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.DeleteSessionEntityType]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py index 250c5a11..5ce3f417 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import pagers from google.cloud.dialogflowcx_v3beta1.types import entity_type from google.cloud.dialogflowcx_v3beta1.types import session_entity_type @@ -367,7 +369,7 @@ def list_session_entity_types( request: Union[session_entity_type.ListSessionEntityTypesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSessionEntityTypesPager: @@ -455,7 +457,7 @@ def get_session_entity_type( request: Union[session_entity_type.GetSessionEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session_entity_type.SessionEntityType: @@ -548,7 +550,7 @@ def create_session_entity_type( *, parent: str = None, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: @@ -655,7 +657,7 @@ def update_session_entity_type( *, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: @@ -760,7 +762,7 @@ def delete_session_entity_type( request: Union[session_entity_type.DeleteSessionEntityTypeRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py index efd2dde4..ffb21ea4 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 SessionEntityTypesTransport(abc.ABC): """Abstract transport class for SessionEntityTypes.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py index 20ff39bd..e8e8ab1c 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py index e4d75432..3787ea35 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py @@ -28,13 +28,15 @@ ) import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.types import audio_config from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import session @@ -191,9 +193,9 @@ def __init__( async def detect_intent( self, - request: session.DetectIntentRequest = None, + request: Union[session.DetectIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.DetectIntentResponse: @@ -207,7 +209,7 @@ async def detect_intent( environments `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DetectIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DetectIntentRequest, dict]): The request object. The request to detect user's intent. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -257,7 +259,7 @@ def streaming_detect_intent( self, requests: AsyncIterator[session.StreamingDetectIntentRequest] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> Awaitable[AsyncIterable[session.StreamingDetectIntentResponse]]: @@ -315,23 +317,37 @@ def streaming_detect_intent( Returns: AsyncIterable[google.cloud.dialogflowcx_v3beta1.types.StreamingDetectIntentResponse]: The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. If enable_partial_response is true, the following - N messages (currently 1 <= N <= 4) contain - detect_intent_response. The first (N-1) - detect_intent_responses will have response_type - set to PARTIAL. The last detect_intent_response - has response_type set to FINAL. If response_type - is false, response stream only contains the final - detect_intent_response. + [StreamingDetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.StreamingDetectIntent] + method. + + Multiple response messages (N) can be returned in + order. + + The first (N-1) responses set either the + recognition_result or detect_intent_response field, + depending on the request: + + - If the + StreamingDetectIntentRequest.query_input.audio + field was set, and the + StreamingDetectIntentRequest.enable_partial_response + field was false, the recognition_result field is + populated for each of the (N-1) responses. See the + [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3beta1.StreamingRecognitionResult] + message for details about the result message + sequence. + - If the + StreamingDetectIntentRequest.enable_partial_response + field was true, the detect_intent_response field + is populated for each of the (N-1) responses, + where 1 <= N <= 4. These responses set the + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse.response_type] + field to PARTIAL. + + For the final Nth response message, the + detect_intent_response is fully populated, and + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse.response_type] + is set to FINAL. """ @@ -351,9 +367,9 @@ def streaming_detect_intent( async def match_intent( self, - request: session.MatchIntentRequest = None, + request: Union[session.MatchIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.MatchIntentResponse: @@ -361,7 +377,7 @@ async def match_intent( change the session status. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest, dict]): The request object. Request of [MatchIntent][]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -398,9 +414,9 @@ async def match_intent( async def fulfill_intent( self, - request: session.FulfillIntentRequest = None, + request: Union[session.FulfillIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.FulfillIntentResponse: @@ -413,7 +429,7 @@ async def fulfill_intent( Otherwise, the behavior is undefined. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.FulfillIntentRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.FulfillIntentRequest, dict]): The request object. Request of [FulfillIntent][] retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py b/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py index 87db18ee..d15668bd 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.types import audio_config from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import session @@ -500,7 +502,7 @@ def detect_intent( self, request: Union[session.DetectIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.DetectIntentResponse: @@ -556,7 +558,7 @@ def streaming_detect_intent( self, requests: Iterator[session.StreamingDetectIntentRequest] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> Iterable[session.StreamingDetectIntentResponse]: @@ -614,23 +616,37 @@ def streaming_detect_intent( Returns: Iterable[google.cloud.dialogflowcx_v3beta1.types.StreamingDetectIntentResponse]: The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. If enable_partial_response is true, the following - N messages (currently 1 <= N <= 4) contain - detect_intent_response. The first (N-1) - detect_intent_responses will have response_type - set to PARTIAL. The last detect_intent_response - has response_type set to FINAL. If response_type - is false, response stream only contains the final - detect_intent_response. + [StreamingDetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.StreamingDetectIntent] + method. + + Multiple response messages (N) can be returned in + order. + + The first (N-1) responses set either the + recognition_result or detect_intent_response field, + depending on the request: + + - If the + StreamingDetectIntentRequest.query_input.audio + field was set, and the + StreamingDetectIntentRequest.enable_partial_response + field was false, the recognition_result field is + populated for each of the (N-1) responses. See the + [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3beta1.StreamingRecognitionResult] + message for details about the result message + sequence. + - If the + StreamingDetectIntentRequest.enable_partial_response + field was true, the detect_intent_response field + is populated for each of the (N-1) responses, + where 1 <= N <= 4. These responses set the + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse.response_type] + field to PARTIAL. + + For the final Nth response message, the + detect_intent_response is fully populated, and + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse.response_type] + is set to FINAL. """ @@ -648,7 +664,7 @@ def match_intent( self, request: Union[session.MatchIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.MatchIntentResponse: @@ -696,7 +712,7 @@ def fulfill_intent( self, request: Union[session.FulfillIntentRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> session.FulfillIntentResponse: diff --git a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py index c6e4e5ff..6b1fa71e 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -37,15 +36,6 @@ 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 SessionsTransport(abc.ABC): """Abstract transport class for Sessions.""" @@ -98,7 +88,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -131,29 +121,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py index 1ed18405..3dd70c3d 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 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 f9ecf2ee..613c3eaf 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3beta1.services.test_cases import pagers @@ -189,17 +191,17 @@ def __init__( async def list_test_cases( self, - request: test_case.ListTestCasesRequest = None, + request: Union[test_case.ListTestCasesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTestCasesAsyncPager: r"""Fetches a list of test cases for a given agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest, dict]): The request object. The request message for [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. parent (:class:`str`): @@ -269,17 +271,17 @@ async def list_test_cases( async def batch_delete_test_cases( self, - request: test_case.BatchDeleteTestCasesRequest = None, + request: Union[test_case.BatchDeleteTestCasesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Batch deletes test cases. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.BatchDeleteTestCasesRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.BatchDeleteTestCasesRequest, dict]): The request object. The request message for [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchDeleteTestCases]. parent (:class:`str`): @@ -333,17 +335,17 @@ async def batch_delete_test_cases( async def get_test_case( self, - request: test_case.GetTestCaseRequest = None, + request: Union[test_case.GetTestCaseRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.TestCase: r"""Gets a test case. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetTestCaseRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetTestCaseRequest, dict]): The request object. The request message for [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCase]. name (:class:`str`): @@ -402,18 +404,18 @@ async def get_test_case( async def create_test_case( self, - request: gcdc_test_case.CreateTestCaseRequest = None, + request: Union[gcdc_test_case.CreateTestCaseRequest, dict] = None, *, parent: str = None, test_case: gcdc_test_case.TestCase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_test_case.TestCase: r"""Creates a test case for the given agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateTestCaseRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateTestCaseRequest, dict]): The request object. The request message for [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.CreateTestCase]. parent (:class:`str`): @@ -479,18 +481,18 @@ async def create_test_case( async def update_test_case( self, - request: gcdc_test_case.UpdateTestCaseRequest = None, + request: Union[gcdc_test_case.UpdateTestCaseRequest, dict] = None, *, test_case: gcdc_test_case.TestCase = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_test_case.TestCase: r"""Updates the specified test case. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateTestCaseRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateTestCaseRequest, dict]): The request object. The request message for [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.UpdateTestCase]. test_case (:class:`google.cloud.dialogflowcx_v3beta1.types.TestCase`): @@ -562,9 +564,9 @@ async def update_test_case( async def run_test_case( self, - request: test_case.RunTestCaseRequest = None, + request: Union[test_case.RunTestCaseRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -581,7 +583,7 @@ async def run_test_case( [RunTestCaseResponse][google.cloud.dialogflow.cx.v3beta1.RunTestCaseResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.RunTestCaseRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.RunTestCaseRequest, dict]): The request object. The request message for [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -633,9 +635,9 @@ async def run_test_case( async def batch_run_test_cases( self, - request: test_case.BatchRunTestCasesRequest = None, + request: Union[test_case.BatchRunTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -652,7 +654,7 @@ async def batch_run_test_cases( [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesRequest, dict]): The request object. The request message for [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -704,16 +706,16 @@ async def batch_run_test_cases( async def calculate_coverage( self, - request: test_case.CalculateCoverageRequest = None, + request: Union[test_case.CalculateCoverageRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.CalculateCoverageResponse: r"""Calculates the test coverage for an agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageRequest, dict]): The request object. The request message for [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -753,9 +755,9 @@ async def calculate_coverage( async def import_test_cases( self, - request: test_case.ImportTestCasesRequest = None, + request: Union[test_case.ImportTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -775,7 +777,7 @@ async def import_test_cases( [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesRequest, dict]): The request object. The request message for [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -827,9 +829,9 @@ async def import_test_cases( async def export_test_cases( self, - request: test_case.ExportTestCasesRequest = None, + request: Union[test_case.ExportTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -848,7 +850,7 @@ async def export_test_cases( [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesResponse] Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest, dict]): The request object. The request message for [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -900,17 +902,17 @@ async def export_test_cases( async def list_test_case_results( self, - request: test_case.ListTestCaseResultsRequest = None, + request: Union[test_case.ListTestCaseResultsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTestCaseResultsAsyncPager: r"""Fetches a list of results for a given test case. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsRequest, dict]): The request object. The request message for [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. parent (:class:`str`): @@ -982,17 +984,17 @@ async def list_test_case_results( async def get_test_case_result( self, - request: test_case.GetTestCaseResultRequest = None, + request: Union[test_case.GetTestCaseResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.TestCaseResult: r"""Gets a test case result. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetTestCaseResultRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetTestCaseResultRequest, dict]): The request object. The request message for [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCaseResult]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py b/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py index 5def82ce..e062da09 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3beta1.services.test_cases import pagers @@ -520,7 +522,7 @@ def list_test_cases( request: Union[test_case.ListTestCasesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTestCasesPager: @@ -600,7 +602,7 @@ def batch_delete_test_cases( request: Union[test_case.BatchDeleteTestCasesRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -664,7 +666,7 @@ def get_test_case( request: Union[test_case.GetTestCaseRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.TestCase: @@ -734,7 +736,7 @@ def create_test_case( *, parent: str = None, test_case: gcdc_test_case.TestCase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_test_case.TestCase: @@ -811,7 +813,7 @@ def update_test_case( *, test_case: gcdc_test_case.TestCase = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_test_case.TestCase: @@ -892,7 +894,7 @@ def run_test_case( self, request: Union[test_case.RunTestCaseRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -964,7 +966,7 @@ def batch_run_test_cases( self, request: Union[test_case.BatchRunTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1036,7 +1038,7 @@ def calculate_coverage( self, request: Union[test_case.CalculateCoverageRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.CalculateCoverageResponse: @@ -1086,7 +1088,7 @@ def import_test_cases( self, request: Union[test_case.ImportTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1161,7 +1163,7 @@ def export_test_cases( self, request: Union[test_case.ExportTestCasesRequest, dict] = None, *, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -1236,7 +1238,7 @@ def list_test_case_results( request: Union[test_case.ListTestCaseResultsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTestCaseResultsPager: @@ -1318,7 +1320,7 @@ def get_test_case_result( request: Union[test_case.GetTestCaseResultRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> test_case.TestCaseResult: diff --git a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py index 15a45c93..45218af5 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 TestCasesTransport(abc.ABC): """Abstract transport class for TestCases.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { @@ -217,7 +184,7 @@ def close(self): raise NotImplementedError() @property - def operations_client(self) -> operations_v1.OperationsClient: + def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() 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 e9cf28d1..20d68a6e 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py @@ -116,7 +116,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) 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 6b96c415..78f8fbc3 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 @@ -21,7 +21,6 @@ from google.api_core import operations_v1 # 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 @@ -163,7 +162,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) diff --git a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py index adbb7567..8d72cf1e 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import pagers from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import transition_route_group @@ -185,10 +187,12 @@ def __init__( async def list_transition_route_groups( self, - request: transition_route_group.ListTransitionRouteGroupsRequest = None, + request: Union[ + transition_route_group.ListTransitionRouteGroupsRequest, dict + ] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTransitionRouteGroupsAsyncPager: @@ -196,7 +200,7 @@ async def list_transition_route_groups( the specified flow. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsRequest, dict]): The request object. The request message for [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. parent (:class:`str`): @@ -267,10 +271,12 @@ async def list_transition_route_groups( async def get_transition_route_group( self, - request: transition_route_group.GetTransitionRouteGroupRequest = None, + request: Union[ + transition_route_group.GetTransitionRouteGroupRequest, dict + ] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> transition_route_group.TransitionRouteGroup: @@ -278,7 +284,7 @@ async def get_transition_route_group( [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetTransitionRouteGroupRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetTransitionRouteGroupRequest, dict]): The request object. The request message for [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.GetTransitionRouteGroup]. name (:class:`str`): @@ -343,11 +349,13 @@ async def get_transition_route_group( async def create_transition_route_group( self, - request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, + request: Union[ + gcdc_transition_route_group.CreateTransitionRouteGroupRequest, dict + ] = None, *, parent: str = None, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_transition_route_group.TransitionRouteGroup: @@ -360,7 +368,7 @@ async def create_transition_route_group( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateTransitionRouteGroupRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateTransitionRouteGroupRequest, dict]): The request object. The request message for [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.CreateTransitionRouteGroup]. parent (:class:`str`): @@ -434,11 +442,13 @@ async def create_transition_route_group( async def update_transition_route_group( self, - request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, + request: Union[ + gcdc_transition_route_group.UpdateTransitionRouteGroupRequest, dict + ] = None, *, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_transition_route_group.TransitionRouteGroup: @@ -450,7 +460,7 @@ async def update_transition_route_group( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateTransitionRouteGroupRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateTransitionRouteGroupRequest, dict]): The request object. The request message for [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.UpdateTransitionRouteGroup]. transition_route_group (:class:`google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup`): @@ -524,10 +534,12 @@ async def update_transition_route_group( async def delete_transition_route_group( self, - request: transition_route_group.DeleteTransitionRouteGroupRequest = None, + request: Union[ + transition_route_group.DeleteTransitionRouteGroupRequest, dict + ] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -539,7 +551,7 @@ async def delete_transition_route_group( documentation `__. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteTransitionRouteGroupRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteTransitionRouteGroupRequest, dict]): The request object. The request message for [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.DeleteTransitionRouteGroup]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py index 95d819bf..316a865b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import pagers from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import transition_route_group @@ -435,7 +437,7 @@ def list_transition_route_groups( ] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTransitionRouteGroupsPager: @@ -523,7 +525,7 @@ def get_transition_route_group( ] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> transition_route_group.TransitionRouteGroup: @@ -606,7 +608,7 @@ def create_transition_route_group( *, parent: str = None, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_transition_route_group.TransitionRouteGroup: @@ -705,7 +707,7 @@ def update_transition_route_group( *, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_transition_route_group.TransitionRouteGroup: @@ -802,7 +804,7 @@ def delete_transition_route_group( ] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py index b44bde2f..b2488177 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 TransitionRouteGroupsTransport(abc.ABC): """Abstract transport class for TransitionRouteGroups.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py index cb338483..28dee288 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py index 7f9a0b9f..63b0d4b3 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3beta1.services.versions import pagers @@ -165,10 +167,10 @@ def __init__( async def list_versions( self, - request: version.ListVersionsRequest = None, + request: Union[version.ListVersionsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListVersionsAsyncPager: @@ -176,7 +178,7 @@ async def list_versions( [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListVersionsRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListVersionsRequest, dict]): The request object. The request message for [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.Versions.ListVersions]. parent (:class:`str`): @@ -248,10 +250,10 @@ async def list_versions( async def get_version( self, - request: version.GetVersionRequest = None, + request: Union[version.GetVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> version.Version: @@ -259,7 +261,7 @@ async def get_version( [Version][google.cloud.dialogflow.cx.v3beta1.Version]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetVersionRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetVersionRequest, dict]): The request object. The request message for [Versions.GetVersion][google.cloud.dialogflow.cx.v3beta1.Versions.GetVersion]. name (:class:`str`): @@ -320,11 +322,11 @@ async def get_version( async def create_version( self, - request: gcdc_version.CreateVersionRequest = None, + request: Union[gcdc_version.CreateVersionRequest, dict] = None, *, parent: str = None, version: gcdc_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -343,7 +345,7 @@ async def create_version( [Version][google.cloud.dialogflow.cx.v3beta1.Version] Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateVersionRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateVersionRequest, dict]): The request object. The request message for [Versions.CreateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.CreateVersion]. parent (:class:`str`): @@ -426,11 +428,11 @@ async def create_version( async def update_version( self, - request: gcdc_version.UpdateVersionRequest = None, + request: Union[gcdc_version.UpdateVersionRequest, dict] = None, *, version: gcdc_version.Version = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_version.Version: @@ -438,7 +440,7 @@ async def update_version( [Version][google.cloud.dialogflow.cx.v3beta1.Version]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateVersionRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateVersionRequest, dict]): The request object. The request message for [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.UpdateVersion]. version (:class:`google.cloud.dialogflowcx_v3beta1.types.Version`): @@ -507,10 +509,10 @@ async def update_version( async def delete_version( self, - request: version.DeleteVersionRequest = None, + request: Union[version.DeleteVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -518,7 +520,7 @@ async def delete_version( [Version][google.cloud.dialogflow.cx.v3beta1.Version]. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteVersionRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteVersionRequest, dict]): The request object. The request message for [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3beta1.Versions.DeleteVersion]. name (:class:`str`): @@ -574,10 +576,10 @@ async def delete_version( async def load_version( self, - request: version.LoadVersionRequest = None, + request: Union[version.LoadVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: @@ -594,7 +596,7 @@ async def load_version( message `__ Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.LoadVersionRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.LoadVersionRequest, dict]): The request object. The request message for [Versions.LoadVersion][google.cloud.dialogflow.cx.v3beta1.Versions.LoadVersion]. name (:class:`str`): @@ -676,6 +678,84 @@ async def load_version( # Done; return the response. return response + async def compare_versions( + self, + request: Union[version.CompareVersionsRequest, dict] = None, + *, + base_version: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.CompareVersionsResponse: + r"""Compares the specified base version with target + version. + + Args: + request (Union[google.cloud.dialogflowcx_v3beta1.types.CompareVersionsRequest, dict]): + The request object. The request message for + [Versions.CompareVersions][google.cloud.dialogflow.cx.v3beta1.Versions.CompareVersions]. + base_version (:class:`str`): + Required. Name of the base flow version to compare with + the target version. Use version ID ``0`` to indicate the + draft version of the specified flow. + + Format: + ``projects//locations//agents/ /flows//versions/``. + + This corresponds to the ``base_version`` 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.CompareVersionsResponse: + The response message for + [Versions.CompareVersions][google.cloud.dialogflow.cx.v3beta1.Versions.CompareVersions]. + + """ + # 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([base_version]) + 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 = version.CompareVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if base_version is not None: + request.base_version = base_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compare_versions, + 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( + (("base_version", request.base_version),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + async def __aenter__(self): return self diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/client.py b/google/cloud/dialogflowcx_v3beta1/services/versions/client.py index ad13b280..57361ac8 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflowcx_v3beta1.services.versions import pagers @@ -362,7 +364,7 @@ def list_versions( request: Union[version.ListVersionsRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListVersionsPager: @@ -445,7 +447,7 @@ def get_version( request: Union[version.GetVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> version.Version: @@ -518,7 +520,7 @@ def create_version( *, parent: str = None, version: gcdc_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -624,7 +626,7 @@ def update_version( *, version: gcdc_version.Version = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_version.Version: @@ -704,7 +706,7 @@ def delete_version( request: Union[version.DeleteVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: @@ -771,7 +773,7 @@ def load_version( request: Union[version.LoadVersionRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: @@ -870,6 +872,84 @@ def load_version( # Done; return the response. return response + def compare_versions( + self, + request: Union[version.CompareVersionsRequest, dict] = None, + *, + base_version: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.CompareVersionsResponse: + r"""Compares the specified base version with target + version. + + Args: + request (Union[google.cloud.dialogflowcx_v3beta1.types.CompareVersionsRequest, dict]): + The request object. The request message for + [Versions.CompareVersions][google.cloud.dialogflow.cx.v3beta1.Versions.CompareVersions]. + base_version (str): + Required. Name of the base flow version to compare with + the target version. Use version ID ``0`` to indicate the + draft version of the specified flow. + + Format: + ``projects//locations//agents/ /flows//versions/``. + + This corresponds to the ``base_version`` 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.CompareVersionsResponse: + The response message for + [Versions.CompareVersions][google.cloud.dialogflow.cx.v3beta1.Versions.CompareVersions]. + + """ + # 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([base_version]) + 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 version.CompareVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.CompareVersionsRequest): + request = version.CompareVersionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if base_version is not None: + request.base_version = base_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compare_versions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("base_version", request.base_version),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + def __enter__(self): return self diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py index 4302c448..96dc75e2 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -41,15 +40,6 @@ 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 VersionsTransport(abc.ABC): """Abstract transport class for Versions.""" @@ -102,7 +92,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -135,29 +125,6 @@ def __init__( # 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 = { @@ -179,6 +146,9 @@ def _prep_wrapped_messages(self, client_info): self.load_version: gapic_v1.method.wrap_method( self.load_version, default_timeout=None, client_info=client_info, ), + self.compare_versions: gapic_v1.method.wrap_method( + self.compare_versions, default_timeout=None, client_info=client_info, + ), } def close(self): @@ -191,7 +161,7 @@ def close(self): raise NotImplementedError() @property - def operations_client(self) -> operations_v1.OperationsClient: + def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() @@ -248,5 +218,16 @@ def load_version( ]: raise NotImplementedError() + @property + def compare_versions( + self, + ) -> Callable[ + [version.CompareVersionsRequest], + Union[ + version.CompareVersionsResponse, Awaitable[version.CompareVersionsResponse] + ], + ]: + raise NotImplementedError() + __all__ = ("VersionsTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py index 9747ccbe..230e8c0b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py @@ -115,7 +115,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -425,6 +425,33 @@ def load_version( ) return self._stubs["load_version"] + @property + def compare_versions( + self, + ) -> Callable[[version.CompareVersionsRequest], version.CompareVersionsResponse]: + r"""Return a callable for the compare versions method over gRPC. + + Compares the specified base version with target + version. + + Returns: + Callable[[~.CompareVersionsRequest], + ~.CompareVersionsResponse]: + 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 "compare_versions" not in self._stubs: + self._stubs["compare_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Versions/CompareVersions", + request_serializer=version.CompareVersionsRequest.serialize, + response_deserializer=version.CompareVersionsResponse.deserialize, + ) + return self._stubs["compare_versions"] + def close(self): self.grpc_channel.close() 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 3048bea6..a1d04a3b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py @@ -21,7 +21,6 @@ from google.api_core import operations_v1 # 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 @@ -162,7 +161,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} - self._operations_client = None + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -436,6 +435,35 @@ def load_version( ) return self._stubs["load_version"] + @property + def compare_versions( + self, + ) -> Callable[ + [version.CompareVersionsRequest], Awaitable[version.CompareVersionsResponse] + ]: + r"""Return a callable for the compare versions method over gRPC. + + Compares the specified base version with target + version. + + Returns: + Callable[[~.CompareVersionsRequest], + Awaitable[~.CompareVersionsResponse]]: + 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 "compare_versions" not in self._stubs: + self._stubs["compare_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Versions/CompareVersions", + request_serializer=version.CompareVersionsRequest.serialize, + response_deserializer=version.CompareVersionsResponse.deserialize, + ) + return self._stubs["compare_versions"] + def close(self): return self.grpc_channel.close() diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py index 4e565c2f..1fcce93c 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py @@ -19,13 +19,15 @@ 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.client_options import 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 +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.webhooks import pagers from google.cloud.dialogflowcx_v3beta1.types import webhook from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook @@ -162,10 +164,10 @@ def __init__( async def list_webhooks( self, - request: webhook.ListWebhooksRequest = None, + request: Union[webhook.ListWebhooksRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListWebhooksAsyncPager: @@ -173,7 +175,7 @@ async def list_webhooks( agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.ListWebhooksRequest, dict]): The request object. The request message for [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. parent (:class:`str`): @@ -243,17 +245,17 @@ async def list_webhooks( async def get_webhook( self, - request: webhook.GetWebhookRequest = None, + request: Union[webhook.GetWebhookRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> webhook.Webhook: r"""Retrieves the specified webhook. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetWebhookRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.GetWebhookRequest, dict]): The request object. The request message for [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.GetWebhook]. name (:class:`str`): @@ -319,18 +321,18 @@ async def get_webhook( async def create_webhook( self, - request: gcdc_webhook.CreateWebhookRequest = None, + request: Union[gcdc_webhook.CreateWebhookRequest, dict] = None, *, parent: str = None, webhook: gcdc_webhook.Webhook = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_webhook.Webhook: r"""Creates a webhook in the specified agent. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateWebhookRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.CreateWebhookRequest, dict]): The request object. The request message for [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook]. parent (:class:`str`): @@ -403,18 +405,18 @@ async def create_webhook( async def update_webhook( self, - request: gcdc_webhook.UpdateWebhookRequest = None, + request: Union[gcdc_webhook.UpdateWebhookRequest, dict] = None, *, webhook: gcdc_webhook.Webhook = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_webhook.Webhook: r"""Updates the specified webhook. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateWebhookRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.UpdateWebhookRequest, dict]): The request object. The request message for [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook]. webhook (:class:`google.cloud.dialogflowcx_v3beta1.types.Webhook`): @@ -490,17 +492,17 @@ async def update_webhook( async def delete_webhook( self, - request: webhook.DeleteWebhookRequest = None, + request: Union[webhook.DeleteWebhookRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified webhook. Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteWebhookRequest`): + request (Union[google.cloud.dialogflowcx_v3beta1.types.DeleteWebhookRequest, dict]): The request object. The request message for [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.DeleteWebhook]. name (:class:`str`): diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py index 431352dc..7a8e4f29 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.dialogflowcx_v3beta1.services.webhooks import pagers from google.cloud.dialogflowcx_v3beta1.types import webhook from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook @@ -371,7 +373,7 @@ def list_webhooks( request: Union[webhook.ListWebhooksRequest, dict] = None, *, parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListWebhooksPager: @@ -452,7 +454,7 @@ def get_webhook( request: Union[webhook.GetWebhookRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> webhook.Webhook: @@ -529,7 +531,7 @@ def create_webhook( *, parent: str = None, webhook: gcdc_webhook.Webhook = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_webhook.Webhook: @@ -613,7 +615,7 @@ def update_webhook( *, webhook: gcdc_webhook.Webhook = None, update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_webhook.Webhook: @@ -699,7 +701,7 @@ def delete_webhook( request: Union[webhook.DeleteWebhookRequest, dict] = None, *, name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py index 972374cd..227881f2 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -39,15 +38,6 @@ 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 WebhooksTransport(abc.ABC): """Abstract transport class for Webhooks.""" @@ -100,7 +90,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -133,29 +123,6 @@ def __init__( # 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 = { diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py index 1b34b29a..055116ff 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ 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 diff --git a/google/cloud/dialogflowcx_v3beta1/types/__init__.py b/google/cloud/dialogflowcx_v3beta1/types/__init__.py index b81c76bd..50d69e71 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/types/__init__.py @@ -41,6 +41,12 @@ SpeechModelVariant, SsmlVoiceGender, ) +from .changelog import ( + Changelog, + GetChangelogRequest, + ListChangelogsRequest, + ListChangelogsResponse, +) from .deployment import ( Deployment, GetDeploymentRequest, @@ -222,6 +228,8 @@ ValidationMessage, ) from .version import ( + CompareVersionsRequest, + CompareVersionsResponse, CreateVersionOperationMetadata, CreateVersionRequest, DeleteVersionRequest, @@ -271,6 +279,10 @@ "OutputAudioEncoding", "SpeechModelVariant", "SsmlVoiceGender", + "Changelog", + "GetChangelogRequest", + "ListChangelogsRequest", + "ListChangelogsResponse", "Deployment", "GetDeploymentRequest", "ListDeploymentsRequest", @@ -425,6 +437,8 @@ "UpdateTransitionRouteGroupRequest", "ResourceName", "ValidationMessage", + "CompareVersionsRequest", + "CompareVersionsResponse", "CreateVersionOperationMetadata", "CreateVersionRequest", "DeleteVersionRequest", diff --git a/google/cloud/dialogflowcx_v3beta1/types/agent.py b/google/cloud/dialogflowcx_v3beta1/types/agent.py index 8440ad5f..f72e8278 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/agent.py +++ b/google/cloud/dialogflowcx_v3beta1/types/agent.py @@ -284,13 +284,22 @@ class ExportAgentResponse(proto.Message): r"""The response message for [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: agent_uri (str): The URI to a file containing the exported agent. This field is populated only if ``agent_uri`` is specified in [ExportAgentRequest][google.cloud.dialogflow.cx.v3beta1.ExportAgentRequest]. + This field is a member of `oneof`_ ``agent``. agent_content (bytes): Uncompressed raw byte content for agent. + This field is a member of `oneof`_ ``agent``. """ agent_uri = proto.Field(proto.STRING, number=1, oneof="agent",) @@ -301,6 +310,13 @@ class RestoreAgentRequest(proto.Message): r"""The request message for [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3beta1.Agents.RestoreAgent]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Required. The name of the agent to restore into. Format: @@ -310,8 +326,10 @@ class RestoreAgentRequest(proto.Message): Storage `__ URI to restore agent from. The format of this URI must be ``gs:///``. + This field is a member of `oneof`_ ``agent``. agent_content (bytes): Uncompressed raw byte content for agent. + This field is a member of `oneof`_ ``agent``. restore_option (google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest.RestoreOption): Agent restore mode. If not specified, ``KEEP`` is assumed. """ diff --git a/google/cloud/dialogflowcx_v3beta1/types/changelog.py b/google/cloud/dialogflowcx_v3beta1/types/changelog.py new file mode 100644 index 00000000..c395ee56 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/types/changelog.py @@ -0,0 +1,139 @@ +# -*- 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={ + "ListChangelogsRequest", + "ListChangelogsResponse", + "GetChangelogRequest", + "Changelog", + }, +) + + +class ListChangelogsRequest(proto.Message): + r"""The request message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3beta1.Changelogs.ListChangelogs]. + + Attributes: + parent (str): + Required. The agent containing the changelogs. Format: + ``projects//locations//agents/``. + filter (str): + The filter string. Supports filter by user_email, resource, + type and create_time. Some examples: + + 1. By user email: user_email = "someone@google.com" + 2. By resource name: resource = + "projects/123/locations/global/agents/456/flows/789" + 3. By resource display name: display_name = "my agent" + 4. By action: action = "Create" + 5. By type: type = "flows" + 6. By create time. Currently predicates on ``create_time`` + and ``create_time_epoch_seconds`` are supported: + create_time_epoch_seconds > 1551790877 AND create_time <= + 2017-01-15T01:30:15.01Z + 7. Combination of above filters: resource = + "projects/123/locations/global/agents/456/flows/789" AND + user_email = "someone@google.com" AND create_time <= + 2017-01-15T01:30:15.01Z + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) + + +class ListChangelogsResponse(proto.Message): + r"""The response message for + [Changelogs.ListChangelogs][google.cloud.dialogflow.cx.v3beta1.Changelogs.ListChangelogs]. + + Attributes: + changelogs (Sequence[google.cloud.dialogflowcx_v3beta1.types.Changelog]): + The list of changelogs. There will be a maximum number of + items returned based on the page_size field in the request. + The changelogs will be ordered by timestamp. + 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 + + changelogs = proto.RepeatedField(proto.MESSAGE, number=1, message="Changelog",) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetChangelogRequest(proto.Message): + r"""The request message for + [Changelogs.GetChangelog][google.cloud.dialogflow.cx.v3beta1.Changelogs.GetChangelog]. + + Attributes: + name (str): + Required. The name of the changelog to get. Format: + ``projects//locations//agents//changelogs/``. + """ + + name = proto.Field(proto.STRING, number=1,) + + +class Changelog(proto.Message): + r"""Changelogs represents a change made to a given agent. + + Attributes: + name (str): + The unique identifier of the changelog. Format: + ``projects//locations//agents//changelogs/``. + user_email (str): + Email address of the authenticated user. + display_name (str): + The affected resource display name of the + change. + action (str): + The action of the change. + type_ (str): + The affected resource type. + resource (str): + The affected resource name of the change. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of the change. + """ + + name = proto.Field(proto.STRING, number=1,) + user_email = proto.Field(proto.STRING, number=2,) + display_name = proto.Field(proto.STRING, number=7,) + action = proto.Field(proto.STRING, number=11,) + type_ = proto.Field(proto.STRING, number=8,) + resource = proto.Field(proto.STRING, number=3,) + create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/experiment.py b/google/cloud/dialogflowcx_v3beta1/types/experiment.py index 1b2b5c0a..bf87bf10 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/experiment.py +++ b/google/cloud/dialogflowcx_v3beta1/types/experiment.py @@ -112,6 +112,8 @@ class State(proto.Enum): class Definition(proto.Message): r"""Definition of the experiment. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: condition (str): The condition defines which subset of sessions are selected @@ -122,6 +124,7 @@ class Definition(proto.Message): version_variants (google.cloud.dialogflowcx_v3beta1.types.VersionVariants): The flow versions as the variants of this experiment. + This field is a member of `oneof`_ ``variants``. """ condition = proto.Field(proto.STRING, number=1,) @@ -184,6 +187,13 @@ class ConfidenceInterval(proto.Message): class Metric(proto.Message): r"""Metric and corresponding confidence intervals. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: type_ (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.MetricType): Ratio-based metric type. Only one of type or count_type is @@ -193,8 +203,10 @@ class Metric(proto.Message): specified in each Metric. ratio (float): Ratio value of a metric. + This field is a member of `oneof`_ ``value``. count (float): Count value of a metric. + This field is a member of `oneof`_ ``value``. confidence_interval (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.ConfidenceInterval): The probability that the treatment is better than all other treatments in the experiment @@ -367,9 +379,12 @@ class RolloutState(proto.Message): class VariantsHistory(proto.Message): r"""The history of variants update. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: version_variants (google.cloud.dialogflowcx_v3beta1.types.VersionVariants): The flow versions as the variants. + This field is a member of `oneof`_ ``variants``. update_time (google.protobuf.timestamp_pb2.Timestamp): Update time of the variants. """ diff --git a/google/cloud/dialogflowcx_v3beta1/types/flow.py b/google/cloud/dialogflowcx_v3beta1/types/flow.py index 6383008a..589bd380 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/flow.py +++ b/google/cloud/dialogflowcx_v3beta1/types/flow.py @@ -420,6 +420,13 @@ class ImportFlowRequest(proto.Message): r"""The request message for [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: parent (str): Required. The agent to import the flow into. Format: @@ -429,8 +436,10 @@ class ImportFlowRequest(proto.Message): Storage `__ URI to import flow from. The format of this URI must be ``gs:///``. + This field is a member of `oneof`_ ``flow``. flow_content (bytes): Uncompressed raw byte content for flow. + This field is a member of `oneof`_ ``flow``. import_option (google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest.ImportOption): Flow import mode. If not specified, ``KEEP`` is assumed. """ @@ -488,13 +497,22 @@ class ExportFlowResponse(proto.Message): r"""The response message for [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: flow_uri (str): The URI to a file containing the exported flow. This field is populated only if ``flow_uri`` is specified in [ExportFlowRequest][google.cloud.dialogflow.cx.v3beta1.ExportFlowRequest]. + This field is a member of `oneof`_ ``flow``. flow_content (bytes): Uncompressed raw byte content for flow. + This field is a member of `oneof`_ ``flow``. """ flow_uri = proto.Field(proto.STRING, number=1, oneof="flow",) diff --git a/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py b/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py index b3c3bf6d..92264d5b 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py +++ b/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py @@ -122,11 +122,20 @@ class CaseContent(proto.Message): r"""The list of messages or conditional cases to activate for this case. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: message (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage): Returned message. + This field is a member of `oneof`_ ``cases_or_message``. additional_cases (google.cloud.dialogflowcx_v3beta1.types.Fulfillment.ConditionalCases): Additional cases to be evaluated. + This field is a member of `oneof`_ ``cases_or_message``. """ message = proto.Field( diff --git a/google/cloud/dialogflowcx_v3beta1/types/page.py b/google/cloud/dialogflowcx_v3beta1/types/page.py index 27b2d1bd..31ff12d4 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/page.py +++ b/google/cloud/dialogflowcx_v3beta1/types/page.py @@ -276,6 +276,13 @@ class EventHandler(proto.Message): associated with the event, the session will transition into the specified flow. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Output only. The unique identifier of this @@ -291,9 +298,11 @@ class EventHandler(proto.Message): target_page (str): The target page to transition to. Format: ``projects//locations//agents//flows//pages/``. + This field is a member of `oneof`_ ``target``. target_flow (str): The target flow to transition to. Format: ``projects//locations//agents//flows/``. + This field is a member of `oneof`_ ``target``. """ name = proto.Field(proto.STRING, number=6,) @@ -324,6 +333,13 @@ class TransitionRoute(proto.Message): associated with the transition, the session will transition into the specified flow. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Output only. The unique identifier of this @@ -357,9 +373,11 @@ class TransitionRoute(proto.Message): target_page (str): The target page to transition to. Format: ``projects//locations//agents//flows//pages/``. + This field is a member of `oneof`_ ``target``. target_flow (str): The target flow to transition to. Format: ``projects//locations//agents//flows/``. + This field is a member of `oneof`_ ``target``. """ name = proto.Field(proto.STRING, number=6,) diff --git a/google/cloud/dialogflowcx_v3beta1/types/response_message.py b/google/cloud/dialogflowcx_v3beta1/types/response_message.py index 75272011..5b4b233d 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/response_message.py +++ b/google/cloud/dialogflowcx_v3beta1/types/response_message.py @@ -45,21 +45,33 @@ class ResponseMessage(proto.Message): scenarios, where the text displayed to the user may differ from what is heard. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: text (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.Text): Returns a text response. + This field is a member of `oneof`_ ``message``. payload (google.protobuf.struct_pb2.Struct): Returns a response containing a custom, platform-specific payload. + This field is a member of `oneof`_ ``message``. conversation_success (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.ConversationSuccess): Indicates that the conversation succeeded. + This field is a member of `oneof`_ ``message``. output_audio_text (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.OutputAudioText): A text or ssml response that is preferentially used for TTS output audio synthesis, as described in the comment on the ResponseMessage message. + This field is a member of `oneof`_ ``message``. live_agent_handoff (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.LiveAgentHandoff): Hands off conversation to a human agent. + This field is a member of `oneof`_ ``message``. end_interaction (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.EndInteraction): Output only. A signal that indicates the interaction with the Dialogflow agent has ended. This message is generated by @@ -69,12 +81,14 @@ class ResponseMessage(proto.Message): It's guaranteed that there is at most one such message in each response. + This field is a member of `oneof`_ ``message``. play_audio (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.PlayAudio): Signal that the client should play an audio clip hosted at a client-specific URI. Dialogflow uses this to construct [mixed_audio][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.mixed_audio]. However, Dialogflow itself does not try to read or process the URI in any way. + This field is a member of `oneof`_ ``message``. mixed_audio (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.MixedAudio): Output only. An audio response message composed of both the synthesized Dialogflow agent responses and responses defined @@ -82,6 +96,7 @@ class ResponseMessage(proto.Message): [play_audio][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.play_audio]. This message is generated by Dialogflow only and not supposed to be defined by the user. + This field is a member of `oneof`_ ``message``. """ class Text(proto.Message): @@ -159,12 +174,21 @@ class OutputAudioText(proto.Message): output audio synthesis, as described in the comment on the ResponseMessage message. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: text (str): The raw text to be synthesized. + This field is a member of `oneof`_ ``source``. ssml (str): The SSML text to be synthesized. For more information, see `SSML `__. + This field is a member of `oneof`_ ``source``. allow_playback_interruption (bool): Output only. Whether the playback of this message can be interrupted by the end user's @@ -219,15 +243,24 @@ class MixedAudio(proto.Message): class Segment(proto.Message): r"""Represents one segment of audio. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: audio (bytes): Raw audio synthesized from the Dialogflow agent's response using the output config specified in the request. + This field is a member of `oneof`_ ``content``. uri (str): Client-specific URI that points to an audio clip accessible to the client. Dialogflow does not impose any validation on it. + This field is a member of `oneof`_ ``content``. allow_playback_interruption (bool): Output only. Whether the playback of this segment can be interrupted by the end user's diff --git a/google/cloud/dialogflowcx_v3beta1/types/security_settings.py b/google/cloud/dialogflowcx_v3beta1/types/security_settings.py index f824a010..1d00315c 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/security_settings.py +++ b/google/cloud/dialogflowcx_v3beta1/types/security_settings.py @@ -148,6 +148,9 @@ class SecuritySettings(proto.Message): on the settings to propagate to all the related components and take effect. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Resource name of the settings. Required for the @@ -170,6 +173,11 @@ class SecuritySettings(proto.Message): `DLP `__ inspect template name. Use this template to define inspect base settings. + The ``DLP Inspect Templates Reader`` role is needed on the + Dialogflow service identity service account (has the form + ``service-PROJECT_NUMBER@gcp-sa-dialogflow.iam.gserviceaccount.com``) + for your agent's project. + If empty, we use the default DLP inspect config. The template name will have one of the following formats: @@ -184,6 +192,12 @@ class SecuritySettings(proto.Message): template name. Use this template to define de-identification configuration for the content. + The ``DLP De-identify Templates Reader`` role is needed on + the Dialogflow service identity service account (has the + form + ``service-PROJECT_NUMBER@gcp-sa-dialogflow.iam.gserviceaccount.com``) + for your agent's project. + If empty, Dialogflow replaces sensitive info with ``[redacted]`` text. @@ -199,14 +213,15 @@ class SecuritySettings(proto.Message): specified number of days. This does not apply to Cloud logging, which is owned by the user - not Dialogflow. - User must Set a value lower than Dialogflow's - default 30d TTL. Setting a value higher than + User must set a value lower than Dialogflow's + default 365d TTL. Setting a value higher than that has no effect. A missing value or setting to 0 also means we use Dialogflow's default TTL. Note: Interaction logging is a limited access feature. Talk to your Google representative to check availability for you. + This field is a member of `oneof`_ ``data_retention``. purge_data_types (Sequence[google.cloud.dialogflowcx_v3beta1.types.SecuritySettings.PurgeDataType]): List of types of data to remove when retention settings triggers purge. diff --git a/google/cloud/dialogflowcx_v3beta1/types/session.py b/google/cloud/dialogflowcx_v3beta1/types/session.py index a32a72d4..e4afc92c 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/session.py +++ b/google/cloud/dialogflowcx_v3beta1/types/session.py @@ -223,30 +223,49 @@ class StreamingDetectIntentRequest(proto.Message): class StreamingDetectIntentResponse(proto.Message): - r"""The top-level message returned from the ``StreamingDetectIntent`` + r"""The top-level message returned from the + [StreamingDetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.StreamingDetectIntent] method. - Multiple response messages can be returned in order: + Multiple response messages (N) can be returned in order. - 1. If the input was set to streaming audio, the first one or more - messages contain ``recognition_result``. Each - ``recognition_result`` represents a more complete transcript of - what the user said. The last ``recognition_result`` has - ``is_final`` set to ``true``. + The first (N-1) responses set either the ``recognition_result`` or + ``detect_intent_response`` field, depending on the request: - 2. If ``enable_partial_response`` is true, the following N messages - (currently 1 <= N <= 4) contain ``detect_intent_response``. The - first (N-1) ``detect_intent_response``\ s will have - ``response_type`` set to ``PARTIAL``. The last - ``detect_intent_response`` has ``response_type`` set to - ``FINAL``. If ``response_type`` is false, response stream only - contains the final ``detect_intent_response``. + - If the ``StreamingDetectIntentRequest.query_input.audio`` field + was set, and the + ``StreamingDetectIntentRequest.enable_partial_response`` field + was false, the ``recognition_result`` field is populated for each + of the (N-1) responses. See the + [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3beta1.StreamingRecognitionResult] + message for details about the result message sequence. + + - If the ``StreamingDetectIntentRequest.enable_partial_response`` + field was true, the ``detect_intent_response`` field is populated + for each of the (N-1) responses, where 1 <= N <= 4. These + responses set the + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse.response_type] + field to ``PARTIAL``. + + For the final Nth response message, the ``detect_intent_response`` + is fully populated, and + [DetectIntentResponse.response_type][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse.response_type] + is set to ``FINAL``. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: recognition_result (google.cloud.dialogflowcx_v3beta1.types.StreamingRecognitionResult): The result of speech recognition. + This field is a member of `oneof`_ ``response``. detect_intent_response (google.cloud.dialogflowcx_v3beta1.types.DetectIntentResponse): The response from detect intent. + This field is a member of `oneof`_ ``response``. """ recognition_result = proto.Field( @@ -262,33 +281,42 @@ class StreamingRecognitionResult(proto.Message): the audio that is currently being processed or an indication that this is the end of the single requested utterance. - Example: - - 1. transcript: "tube" - - 2. transcript: "to be a" - - 3. transcript: "to be" - - 4. transcript: "to be or not to be" is_final: true - - 5. transcript: " that's" - - 6. transcript: " that is" - - 7. message_type: ``END_OF_SINGLE_UTTERANCE`` - - 8. transcript: " that is the question" is_final: true - - Only two of the responses contain final results (#4 and #8 indicated - by ``is_final: true``). Concatenating these generates the full - transcript: "to be or not to be that is the question". - - In each response we populate: - - - for ``TRANSCRIPT``: ``transcript`` and possibly ``is_final``. - - - for ``END_OF_SINGLE_UTTERANCE``: only ``message_type``. + While end-user audio is being processed, Dialogflow sends a series + of results. Each result may contain a ``transcript`` value. A + transcript represents a portion of the utterance. While the + recognizer is processing audio, transcript values may be interim + values or finalized values. Once a transcript is finalized, the + ``is_final`` value is set to true and processing continues for the + next transcript. + + If + ``StreamingDetectIntentRequest.query_input.audio.config.single_utterance`` + was true, and the recognizer has completed processing audio, the + ``message_type`` value is set to \`END_OF_SINGLE_UTTERANCE and the + following (last) result contains the last finalized transcript. + + The complete end-user utterance is determined by concatenating the + finalized transcript values received for the series of results. + + In the following example, single utterance is enabled. In the case + where single utterance is not enabled, result 7 would not occur. + + :: + + Num | transcript | message_type | is_final + --- | ----------------------- | ----------------------- | -------- + 1 | "tube" | TRANSCRIPT | false + 2 | "to be a" | TRANSCRIPT | false + 3 | "to be" | TRANSCRIPT | false + 4 | "to be or not to be" | TRANSCRIPT | true + 5 | "that's" | TRANSCRIPT | false + 6 | "that is | TRANSCRIPT | false + 7 | unset | END_OF_SINGLE_UTTERANCE | unset + 8 | " that is the question" | TRANSCRIPT | true + + Concatenating the finalized transcripts with ``is_final`` set to + true, the complete utterance becomes "to be or not to be that is the + question". Attributes: message_type (google.cloud.dialogflowcx_v3beta1.types.StreamingRecognitionResult.MessageType): @@ -486,18 +514,30 @@ class QueryInput(proto.Message): 4. An event to be triggered. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: text (google.cloud.dialogflowcx_v3beta1.types.TextInput): The natural language text to be processed. + This field is a member of `oneof`_ ``input``. intent (google.cloud.dialogflowcx_v3beta1.types.IntentInput): The intent to be triggered. + This field is a member of `oneof`_ ``input``. audio (google.cloud.dialogflowcx_v3beta1.types.AudioInput): The natural language speech audio to be processed. + This field is a member of `oneof`_ ``input``. event (google.cloud.dialogflowcx_v3beta1.types.EventInput): The event to be triggered. + This field is a member of `oneof`_ ``input``. dtmf (google.cloud.dialogflowcx_v3beta1.types.DtmfInput): The DTMF event to be handled. + This field is a member of `oneof`_ ``input``. language_code (str): Required. The language of the input. See `Language Support `__ @@ -517,30 +557,42 @@ class QueryInput(proto.Message): class QueryResult(proto.Message): r"""Represents the result of a conversational query. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: text (str): If [natural language text][google.cloud.dialogflow.cx.v3beta1.TextInput] was provided as input, this field will contain a copy of the text. + This field is a member of `oneof`_ ``query``. trigger_intent (str): If an [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was provided as input, this field will contain a copy of the intent identifier. Format: ``projects//locations//agents//intents/``. + This field is a member of `oneof`_ ``query``. transcript (str): If [natural language speech audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was provided as input, this field will contain the transcript for the audio. + This field is a member of `oneof`_ ``query``. trigger_event (str): If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] was provided as input, this field will contain the name of the event. + This field is a member of `oneof`_ ``query``. dtmf (google.cloud.dialogflowcx_v3beta1.types.DtmfInput): If a [DTMF][DTMFInput] was provided as input, this field will contain a copy of the [DTMFInput][]. + This field is a member of `oneof`_ ``query``. language_code (str): The language that was triggered during intent detection. See `Language @@ -828,27 +880,38 @@ class MatchIntentRequest(proto.Message): class MatchIntentResponse(proto.Message): r"""Response of [MatchIntent][]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: text (str): If [natural language text][google.cloud.dialogflow.cx.v3beta1.TextInput] was provided as input, this field will contain a copy of the text. + This field is a member of `oneof`_ ``query``. trigger_intent (str): If an [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was provided as input, this field will contain a copy of the intent identifier. Format: ``projects//locations//agents//intents/``. + This field is a member of `oneof`_ ``query``. transcript (str): If [natural language speech audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was provided as input, this field will contain the transcript for the audio. + This field is a member of `oneof`_ ``query``. trigger_event (str): If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] was provided as input, this field will contain a copy of the event name. + This field is a member of `oneof`_ ``query``. matches (Sequence[google.cloud.dialogflowcx_v3beta1.types.Match]): Match results, if more than one, ordered descendingly by the confidence we have that the diff --git a/google/cloud/dialogflowcx_v3beta1/types/test_case.py b/google/cloud/dialogflowcx_v3beta1/types/test_case.py index 30697c8f..357c8ad0 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/test_case.py +++ b/google/cloud/dialogflowcx_v3beta1/types/test_case.py @@ -312,15 +312,24 @@ class TransitionCoverage(proto.Message): class TransitionNode(proto.Message): r"""The source or target of a transition. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: page (google.cloud.dialogflowcx_v3beta1.types.Page): Indicates a transition to a [Page][google.cloud.dialogflow.cx.v3beta1.Page]. Only some fields such as name and displayname will be set. + This field is a member of `oneof`_ ``kind``. flow (google.cloud.dialogflowcx_v3beta1.types.Flow): Indicates a transition to a [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. Only some fields such as name and displayname will be set. + This field is a member of `oneof`_ ``kind``. """ page = proto.Field( @@ -333,6 +342,13 @@ class TransitionNode(proto.Message): class Transition(proto.Message): r"""A transition in a page. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: source (google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage.TransitionNode): The start node of a transition. @@ -346,8 +362,10 @@ class Transition(proto.Message): at least one of the agent's test cases. transition_route (google.cloud.dialogflowcx_v3beta1.types.TransitionRoute): Intent route or condition route. + This field is a member of `oneof`_ ``detail``. event_handler (google.cloud.dialogflowcx_v3beta1.types.EventHandler): Event handler. + This field is a member of `oneof`_ ``detail``. """ source = proto.Field( @@ -489,17 +507,27 @@ class CalculateCoverageResponse(proto.Message): r"""The response message for [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: agent (str): The agent to calculate coverage for. Format: ``projects//locations//agents/``. intent_coverage (google.cloud.dialogflowcx_v3beta1.types.IntentCoverage): Intent coverage. + This field is a member of `oneof`_ ``coverage_type``. transition_coverage (google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage): Transition (excluding transition route groups) coverage. + This field is a member of `oneof`_ ``coverage_type``. route_group_coverage (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroupCoverage): Transition route group coverage. + This field is a member of `oneof`_ ``coverage_type``. """ agent = proto.Field(proto.STRING, number=5,) @@ -750,6 +778,13 @@ class ImportTestCasesRequest(proto.Message): r"""The request message for [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: parent (str): Required. The agent to import test cases to. Format: @@ -759,8 +794,10 @@ class ImportTestCasesRequest(proto.Message): Storage `__ URI to import test cases from. The format of this URI must be ``gs:///``. + This field is a member of `oneof`_ ``source``. content (bytes): Uncompressed raw byte content for test cases. + This field is a member of `oneof`_ ``source``. """ parent = proto.Field(proto.STRING, number=1,) @@ -812,6 +849,9 @@ class ExportTestCasesRequest(proto.Message): r"""The request message for [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: parent (str): Required. The agent where to export test cases from. Format: @@ -822,6 +862,7 @@ class ExportTestCasesRequest(proto.Message): export the test cases to. The format of this URI must be ``gs:///``. If unspecified, the serialized test cases is returned inline. + This field is a member of `oneof`_ ``destination``. data_format (google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest.DataFormat): The data format of the exported test cases. If not specified, ``BLOB`` is assumed. @@ -854,13 +895,22 @@ class ExportTestCasesResponse(proto.Message): r"""The response message for [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: gcs_uri (str): The URI to a file containing the exported test cases. This field is populated only if ``gcs_uri`` is specified in [ExportTestCasesRequest][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesRequest]. + This field is a member of `oneof`_ ``destination``. content (bytes): Uncompressed raw byte content for test cases. + This field is a member of `oneof`_ ``destination``. """ gcs_uri = proto.Field(proto.STRING, number=1, oneof="destination",) diff --git a/google/cloud/dialogflowcx_v3beta1/types/version.py b/google/cloud/dialogflowcx_v3beta1/types/version.py index f5e3de5e..27b474cb 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/version.py +++ b/google/cloud/dialogflowcx_v3beta1/types/version.py @@ -32,6 +32,8 @@ "UpdateVersionRequest", "DeleteVersionRequest", "LoadVersionRequest", + "CompareVersionsRequest", + "CompareVersionsResponse", }, ) @@ -229,4 +231,58 @@ class LoadVersionRequest(proto.Message): allow_override_agent_resources = proto.Field(proto.BOOL, number=2,) +class CompareVersionsRequest(proto.Message): + r"""The request message for + [Versions.CompareVersions][google.cloud.dialogflow.cx.v3beta1.Versions.CompareVersions]. + + Attributes: + base_version (str): + Required. Name of the base flow version to compare with the + target version. Use version ID ``0`` to indicate the draft + version of the specified flow. + + Format: + ``projects//locations//agents/ /flows//versions/``. + target_version (str): + Required. Name of the target flow version to compare with + the base version. Use version ID ``0`` to indicate the draft + version of the specified flow. Format: + ``projects//locations//agents//flows//versions/``. + language_code (str): + The language to compare the flow versions for. + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + base_version = proto.Field(proto.STRING, number=1,) + target_version = proto.Field(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=3,) + + +class CompareVersionsResponse(proto.Message): + r"""The response message for + [Versions.CompareVersions][google.cloud.dialogflow.cx.v3beta1.Versions.CompareVersions]. + + Attributes: + base_version_content_json (str): + JSON representation of the base version + content. + target_version_content_json (str): + JSON representation of the target version + content. + compare_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the two version compares. + """ + + base_version_content_json = proto.Field(proto.STRING, number=1,) + target_version_content_json = proto.Field(proto.STRING, number=2,) + compare_time = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/webhook.py b/google/cloud/dialogflowcx_v3beta1/types/webhook.py index 92a5474c..b8f5d0f4 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/webhook.py +++ b/google/cloud/dialogflowcx_v3beta1/types/webhook.py @@ -46,6 +46,13 @@ class Webhook(proto.Message): responses, validate collected data, or trigger actions on the backend. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): The unique identifier of the webhook. Required for the @@ -59,10 +66,12 @@ class Webhook(proto.Message): webhook, unique within the agent. generic_web_service (google.cloud.dialogflowcx_v3beta1.types.Webhook.GenericWebService): Configuration for a generic web service. + This field is a member of `oneof`_ ``webhook``. service_directory (google.cloud.dialogflowcx_v3beta1.types.Webhook.ServiceDirectoryConfig): Configuration for a `Service Directory `__ service. + This field is a member of `oneof`_ ``webhook``. timeout (google.protobuf.duration_pb2.Duration): Webhook execution timeout. Execution is considered failed if Dialogflow doesn't receive @@ -251,6 +260,13 @@ class WebhookRequest(proto.Message): as a JSON object and the field names will be presented in camel cases. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: detect_intent_response_id (str): Always present. The unique identifier of the @@ -261,21 +277,25 @@ class WebhookRequest(proto.Message): text][google.cloud.dialogflow.cx.v3beta1.TextInput] was provided as input, this field will contain a copy of the text. + This field is a member of `oneof`_ ``query``. trigger_intent (str): If an [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was provided as input, this field will contain a copy of the intent identifier. Format: ``projects//locations//agents//intents/``. + This field is a member of `oneof`_ ``query``. transcript (str): If [natural language speech audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was provided as input, this field will contain the transcript for the audio. + This field is a member of `oneof`_ ``query``. trigger_event (str): If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] was provided as input, this field will contain the name of the event. + This field is a member of `oneof`_ ``query``. language_code (str): The language code specified in the [original request][QueryInput.language_code]. @@ -403,6 +423,13 @@ class SentimentAnalysisResult(proto.Message): class WebhookResponse(proto.Message): r"""The response message for a webhook call. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: fulfillment_response (google.cloud.dialogflowcx_v3beta1.types.WebhookResponse.FulfillmentResponse): The fulfillment response to send to the user. @@ -423,9 +450,11 @@ class WebhookResponse(proto.Message): target_page (str): The target page to transition to. Format: ``projects//locations//agents//flows//pages/``. + This field is a member of `oneof`_ ``transition``. target_flow (str): The target flow to transition to. Format: ``projects//locations//agents//flows/``. + This field is a member of `oneof`_ ``transition``. """ class FulfillmentResponse(proto.Message): diff --git a/noxfile.py b/noxfile.py index 70ed0686..ab589a7e 100644 --- a/noxfile.py +++ b/noxfile.py @@ -101,7 +101,7 @@ def default(session): "py.test", "--quiet", f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=google/cloud", + "--cov=google", "--cov=tests/unit", "--cov-append", "--cov-config=.coveragerc", diff --git a/samples/snippets/detect_intent_stream.py b/samples/snippets/detect_intent_stream.py index d2ad166e..ebe71515 100644 --- a/samples/snippets/detect_intent_stream.py +++ b/samples/snippets/detect_intent_stream.py @@ -73,10 +73,23 @@ def detect_intent_stream(agent, session_id, audio_file_path, language_code): def request_generator(): audio_input = session.AudioInput(config=input_audio_config) query_input = session.QueryInput(audio=audio_input, language_code=language_code) + voice_selection = audio_config.VoiceSelectionParams() + synthesize_speech_config = audio_config.SynthesizeSpeechConfig() + output_audio_config = audio_config.OutputAudioConfig() + + # Sets the voice name and gender + voice_selection.name = "en-GB-Standard-A" + voice_selection.ssml_gender = audio_config.SsmlVoiceGender.SSML_VOICE_GENDER_FEMALE + + synthesize_speech_config.voice = voice_selection + + # Sets the audio encoding + output_audio_config.audio_encoding = audio_config.OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_UNSPECIFIED + output_audio_config.synthesize_speech_config = synthesize_speech_config # The first request contains the configuration. yield session.StreamingDetectIntentRequest( - session=session_path, query_input=query_input + session=session_path, query_input=query_input, output_audio_config=output_audio_config ) # Here we are reading small chunks of audio data from a local diff --git a/samples/snippets/list_training_phrases.py b/samples/snippets/list_training_phrases.py new file mode 100644 index 00000000..11f7417f --- /dev/null +++ b/samples/snippets/list_training_phrases.py @@ -0,0 +1,41 @@ +# Copyright 2021 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 +# +# https://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. + +# [START dialogflow_list_training_phrases] + + +def list_training_phrases(project_id, agent_id, intent_id, location): + """Returns all training phrases for a specified intent.""" + + from google.cloud import dialogflowcx + + # Create the intents client + intent_client = dialogflowcx.IntentsClient() + + # Specify working intent + intent_name = intent_client.intent_path(project_id, location, agent_id, intent_id) + + # Compose the get-intent request + get_intent_request = dialogflowcx.GetIntentRequest(name=intent_name) + + intent = intent_client.get_intent(get_intent_request) + + # Iterate through the training phrases. + for phrase in intent.training_phrases: + print(phrase) + + return intent.training_phrases + + +# [END dialogflow_list_training_phrases] diff --git a/samples/snippets/list_training_phrases_test.py b/samples/snippets/list_training_phrases_test.py new file mode 100644 index 00000000..94d4e74c --- /dev/null +++ b/samples/snippets/list_training_phrases_test.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python + +# Copyright 2021 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 google.auth + +import list_training_phrases + + +_, PROJECT_ID = google.auth.default() +INTENT_ID = os.getenv("INTENT_ID") +LOCATION = "global" +AGENT_ID = os.getenv("AGENT_ID") + + +def test_list_training_phrases(capsys): + training_phrases = list_training_phrases.list_training_phrases( + PROJECT_ID, AGENT_ID, INTENT_ID, LOCATION + ) + assert len(training_phrases) >= 15 # Number of training phrases at this point. diff --git a/samples/snippets/noxfile_config.py b/samples/snippets/noxfile_config.py index 6562b147..995dc281 100644 --- a/samples/snippets/noxfile_config.py +++ b/samples/snippets/noxfile_config.py @@ -35,5 +35,6 @@ "AGENT_ID": "53516802-3e2a-4016-80b6-a3df0d240240", "AGENT_ID_US_CENTRAL1": "edf8372c-c66a-4984-83ba-b85885e95e2a", "AUDIO_PATH": "resources/hello.wav", + "INTENT_ID": "164428bd-647a-4e30-ab0f-cc7f3e3b76f9", }, } diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt index 9299a7a8..92709451 100644 --- a/samples/snippets/requirements-test.txt +++ b/samples/snippets/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.5 \ No newline at end of file +pytest==6.2.5 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index fb9e5d8d..b075c343 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1,2 @@ -google-cloud-dialogflow-cx==1.4.0 +google-cloud-dialogflow-cx==1.5.0 +Flask==2.0.2 diff --git a/samples/snippets/webhook.py b/samples/snippets/webhook.py new file mode 100644 index 00000000..0d85280e --- /dev/null +++ b/samples/snippets/webhook.py @@ -0,0 +1,57 @@ +# Copyright 2021, 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. + +''' handle_webhook will return the correct fullfilment response dependong the tag that is sent in the request''' + +# [START dialogflow_cx_webhook] + + +def handle_webhook(request): + + req = request.get_json() + + tag = req["fulfillmentInfo"]["tag"] + + if tag == "Default Welcome Intent": + # You can also use the google.cloud.dialogflowcx_v3.types.WebhookRequest protos instead of manually writing the json object + # Please see https://googleapis.dev/python/dialogflow/latest/dialogflow_v2/types.html?highlight=webhookresponse#google.cloud.dialogflow_v2.types.WebhookResponse for an overview + res = { + "fulfillment_response": { + "messages": [{"text": {"text": ["Hi from a GCF Webhook"]}}] + } + } + elif tag == "get-name": + res = { + "fulfillment_response": { + "messages": [{"text": {"text": ["My name is Phlowhook"]}}] + } + } + else: + res = { + "fulfillment_response": { + "messages": [ + { + "text": { + "text": [ + f"There are no fulfillment responses defined for {tag} tag" + ] + } + } + ] + } + } + + # Returns json + return res + +# [END dialogflow_cx_webhook] diff --git a/samples/snippets/webhook_test.py b/samples/snippets/webhook_test.py new file mode 100644 index 00000000..dee58ddf --- /dev/null +++ b/samples/snippets/webhook_test.py @@ -0,0 +1,36 @@ +# Copyright 2021, 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. + +"""Test webhook""" + +import flask +import pytest + +from webhook import handle_webhook + +# Create a fake 'app' for generating test request contexts. + +request = { + "fulfillmentInfo": {"tag": "Default Welcome Intent"} +} + + +@pytest.fixture(scope='module') +def app(): + return flask.Flask(__name__) + + +def test_handle_webhook(app): + with app.test_request_context(json=request): + res = handle_webhook(flask.request) + assert 'Hi from a GCF Webhook' in str(res) diff --git a/setup.py b/setup.py index fe952949..800d96d3 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ import os import setuptools # type: ignore -version = "1.5.0" +version = "1.6.0" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -48,9 +48,8 @@ # NOTE: Maintainers, please do not require google-api-core>=2.x.x # Until this issue is closed # https://github.com/googleapis/google-cloud-python/issues/10566 - "google-api-core[grpc] >= 1.26.0, <3.0.0dev", + "google-api-core[grpc] >= 1.28.0, <3.0.0dev", "proto-plus >= 1.4.0", - "packaging >= 14.3", ), python_requires=">=3.6", classifiers=[ @@ -60,6 +59,8 @@ "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", "Topic :: Internet", "Topic :: Software Development :: Libraries :: Python Modules", ], diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 1b1c1ae9..6b451bc3 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -5,7 +5,5 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-api-core==1.26.0 +google-api-core==1.28.0 proto-plus==1.4.0 -packaging==14.3 -google-auth==1.24.0 # TODO: remove when google-auth>=1.25.0 is required through google-api-core diff --git a/tests/unit/gapic/dialogflowcx_v3/test_agents.py b/tests/unit/gapic/dialogflowcx_v3/test_agents.py index 85d06c17..eb66dac2 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_agents.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_agents.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -39,9 +38,6 @@ from google.cloud.dialogflowcx_v3.services.agents import AgentsClient from google.cloud.dialogflowcx_v3.services.agents import pagers from google.cloud.dialogflowcx_v3.services.agents import transports -from google.cloud.dialogflowcx_v3.services.agents.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import advanced_settings from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent @@ -53,20 +49,6 @@ 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" @@ -201,7 +183,7 @@ def test_agents_client_client_options(client_class, transport_class, transport_n 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -218,7 +200,7 @@ def test_agents_client_client_options(client_class, transport_class, transport_n 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -235,7 +217,7 @@ def test_agents_client_client_options(client_class, transport_class, transport_n 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -264,7 +246,7 @@ def test_agents_client_client_options(client_class, transport_class, transport_n 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -319,7 +301,7 @@ def test_agents_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -361,7 +343,7 @@ def test_agents_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -383,7 +365,7 @@ def test_agents_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -410,7 +392,7 @@ def test_agents_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -437,7 +419,7 @@ def test_agents_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2399,7 +2381,6 @@ def test_agents_base_transport(): transport.operations_client -@requires_google_auth_gte_1_25_0 def test_agents_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2423,29 +2404,6 @@ def test_agents_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_agents_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_v3.services.agents.transports.AgentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport( - 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_agents_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( @@ -2457,7 +2415,6 @@ def test_agents_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_agents_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2473,26 +2430,10 @@ def test_agents_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_agents_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) - AgentsClient() - 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.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_agents_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2509,26 +2450,6 @@ def test_agents_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_agents_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_changelogs.py b/tests/unit/gapic/dialogflowcx_v3/test_changelogs.py new file mode 100644 index 00000000..39238532 --- /dev/null +++ b/tests/unit/gapic/dialogflowcx_v3/test_changelogs.py @@ -0,0 +1,1596 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflowcx_v3.services.changelogs import ChangelogsAsyncClient +from google.cloud.dialogflowcx_v3.services.changelogs import ChangelogsClient +from google.cloud.dialogflowcx_v3.services.changelogs import pagers +from google.cloud.dialogflowcx_v3.services.changelogs import transports +from google.cloud.dialogflowcx_v3.types import changelog +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ChangelogsClient._get_default_mtls_endpoint(None) is None + assert ( + ChangelogsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + ChangelogsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ChangelogsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ChangelogsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ChangelogsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ChangelogsClient, ChangelogsAsyncClient,]) +def test_changelogs_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.ChangelogsGrpcTransport, "grpc"), + (transports.ChangelogsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_changelogs_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", [ChangelogsClient, ChangelogsAsyncClient,]) +def test_changelogs_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_changelogs_client_get_transport_class(): + transport = ChangelogsClient.get_transport_class() + available_transports = [ + transports.ChangelogsGrpcTransport, + ] + assert transport in available_transports + + transport = ChangelogsClient.get_transport_class("grpc") + assert transport == transports.ChangelogsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ChangelogsClient, transports.ChangelogsGrpcTransport, "grpc"), + ( + ChangelogsAsyncClient, + transports.ChangelogsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ChangelogsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ChangelogsClient) +) +@mock.patch.object( + ChangelogsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ChangelogsAsyncClient), +) +def test_changelogs_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(ChangelogsClient, "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(ChangelogsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, 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", + [ + (ChangelogsClient, transports.ChangelogsGrpcTransport, "grpc", "true"), + ( + ChangelogsAsyncClient, + transports.ChangelogsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ChangelogsClient, transports.ChangelogsGrpcTransport, "grpc", "false"), + ( + ChangelogsAsyncClient, + transports.ChangelogsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ChangelogsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ChangelogsClient) +) +@mock.patch.object( + ChangelogsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ChangelogsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_changelogs_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(transport=transport_name, 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ChangelogsClient, transports.ChangelogsGrpcTransport, "grpc"), + ( + ChangelogsAsyncClient, + transports.ChangelogsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_changelogs_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(transport=transport_name, 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", + [ + (ChangelogsClient, transports.ChangelogsGrpcTransport, "grpc"), + ( + ChangelogsAsyncClient, + transports.ChangelogsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_changelogs_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(transport=transport_name, 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_changelogs_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflowcx_v3.services.changelogs.transports.ChangelogsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ChangelogsClient(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_changelogs( + transport: str = "grpc", request_type=changelog.ListChangelogsRequest +): + client = ChangelogsClient( + 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_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.ListChangelogsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.ListChangelogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChangelogsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_changelogs_from_dict(): + test_list_changelogs(request_type=dict) + + +def test_list_changelogs_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 = ChangelogsClient( + 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_changelogs), "__call__") as call: + client.list_changelogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.ListChangelogsRequest() + + +@pytest.mark.asyncio +async def test_list_changelogs_async( + transport: str = "grpc_asyncio", request_type=changelog.ListChangelogsRequest +): + client = ChangelogsAsyncClient( + 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_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + changelog.ListChangelogsResponse(next_page_token="next_page_token_value",) + ) + response = await client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.ListChangelogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChangelogsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_changelogs_async_from_dict(): + await test_list_changelogs_async(request_type=dict) + + +def test_list_changelogs_field_headers(): + client = ChangelogsClient(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 = changelog.ListChangelogsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + call.return_value = changelog.ListChangelogsResponse() + client.list_changelogs(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_changelogs_field_headers_async(): + client = ChangelogsAsyncClient(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 = changelog.ListChangelogsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + changelog.ListChangelogsResponse() + ) + await client.list_changelogs(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_changelogs_flattened(): + client = ChangelogsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.ListChangelogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_changelogs(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_changelogs_flattened_error(): + client = ChangelogsClient(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_changelogs( + changelog.ListChangelogsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_changelogs_flattened_async(): + client = ChangelogsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.ListChangelogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + changelog.ListChangelogsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_changelogs(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_changelogs_flattened_error_async(): + client = ChangelogsAsyncClient(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_changelogs( + changelog.ListChangelogsRequest(), parent="parent_value", + ) + + +def test_list_changelogs_pager(): + client = ChangelogsClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + changelog.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + changelog.ListChangelogsResponse(changelogs=[], next_page_token="def",), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(),], next_page_token="ghi", + ), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(), changelog.Changelog(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_changelogs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, changelog.Changelog) for i in results) + + +def test_list_changelogs_pages(): + client = ChangelogsClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + changelog.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + changelog.ListChangelogsResponse(changelogs=[], next_page_token="def",), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(),], next_page_token="ghi", + ), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(), changelog.Changelog(),], + ), + RuntimeError, + ) + pages = list(client.list_changelogs(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_changelogs_async_pager(): + client = ChangelogsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_changelogs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + changelog.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + changelog.ListChangelogsResponse(changelogs=[], next_page_token="def",), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(),], next_page_token="ghi", + ), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(), changelog.Changelog(),], + ), + RuntimeError, + ) + async_pager = await client.list_changelogs(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, changelog.Changelog) for i in responses) + + +@pytest.mark.asyncio +async def test_list_changelogs_async_pages(): + client = ChangelogsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_changelogs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + changelog.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + changelog.ListChangelogsResponse(changelogs=[], next_page_token="def",), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(),], next_page_token="ghi", + ), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(), changelog.Changelog(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_changelogs(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_changelog( + transport: str = "grpc", request_type=changelog.GetChangelogRequest +): + client = ChangelogsClient( + 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_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.Changelog( + name="name_value", + user_email="user_email_value", + display_name="display_name_value", + action="action_value", + type_="type__value", + resource="resource_value", + ) + response = client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.GetChangelogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, changelog.Changelog) + assert response.name == "name_value" + assert response.user_email == "user_email_value" + assert response.display_name == "display_name_value" + assert response.action == "action_value" + assert response.type_ == "type__value" + assert response.resource == "resource_value" + + +def test_get_changelog_from_dict(): + test_get_changelog(request_type=dict) + + +def test_get_changelog_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 = ChangelogsClient( + 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_changelog), "__call__") as call: + client.get_changelog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.GetChangelogRequest() + + +@pytest.mark.asyncio +async def test_get_changelog_async( + transport: str = "grpc_asyncio", request_type=changelog.GetChangelogRequest +): + client = ChangelogsAsyncClient( + 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_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + changelog.Changelog( + name="name_value", + user_email="user_email_value", + display_name="display_name_value", + action="action_value", + type_="type__value", + resource="resource_value", + ) + ) + response = await client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.GetChangelogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, changelog.Changelog) + assert response.name == "name_value" + assert response.user_email == "user_email_value" + assert response.display_name == "display_name_value" + assert response.action == "action_value" + assert response.type_ == "type__value" + assert response.resource == "resource_value" + + +@pytest.mark.asyncio +async def test_get_changelog_async_from_dict(): + await test_get_changelog_async(request_type=dict) + + +def test_get_changelog_field_headers(): + client = ChangelogsClient(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 = changelog.GetChangelogRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + call.return_value = changelog.Changelog() + client.get_changelog(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_changelog_field_headers_async(): + client = ChangelogsAsyncClient(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 = changelog.GetChangelogRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(changelog.Changelog()) + await client.get_changelog(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_changelog_flattened(): + client = ChangelogsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.Changelog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_changelog(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_changelog_flattened_error(): + client = ChangelogsClient(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_changelog( + changelog.GetChangelogRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_changelog_flattened_async(): + client = ChangelogsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.Changelog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(changelog.Changelog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_changelog(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_changelog_flattened_error_async(): + client = ChangelogsAsyncClient(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_changelog( + changelog.GetChangelogRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ChangelogsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChangelogsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ChangelogsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChangelogsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ChangelogsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChangelogsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChangelogsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ChangelogsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChangelogsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ChangelogsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [transports.ChangelogsGrpcTransport, transports.ChangelogsGrpcAsyncIOTransport,], +) +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 = ChangelogsClient(credentials=ga_credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.ChangelogsGrpcTransport,) + + +def test_changelogs_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ChangelogsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_changelogs_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflowcx_v3.services.changelogs.transports.ChangelogsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ChangelogsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_changelogs", + "get_changelog", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_changelogs_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_v3.services.changelogs.transports.ChangelogsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ChangelogsTransport( + 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", + ) + + +def test_changelogs_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_v3.services.changelogs.transports.ChangelogsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ChangelogsTransport() + adc.assert_called_once() + + +def test_changelogs_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) + ChangelogsClient() + 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, + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.ChangelogsGrpcTransport, transports.ChangelogsGrpcAsyncIOTransport,], +) +def test_changelogs_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,grpc_helpers", + [ + (transports.ChangelogsGrpcTransport, grpc_helpers), + (transports.ChangelogsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_changelogs_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.ChangelogsGrpcTransport, transports.ChangelogsGrpcAsyncIOTransport], +) +def test_changelogs_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_changelogs_host_no_port(): + client = ChangelogsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_changelogs_host_with_port(): + client = ChangelogsClient( + 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_changelogs_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ChangelogsGrpcTransport( + 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_changelogs_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ChangelogsGrpcAsyncIOTransport( + 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.ChangelogsGrpcTransport, transports.ChangelogsGrpcAsyncIOTransport], +) +def test_changelogs_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.ChangelogsGrpcTransport, transports.ChangelogsGrpcAsyncIOTransport], +) +def test_changelogs_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_changelog_path(): + project = "squid" + location = "clam" + agent = "whelk" + changelog = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}".format( + project=project, location=location, agent=agent, changelog=changelog, + ) + actual = ChangelogsClient.changelog_path(project, location, agent, changelog) + assert expected == actual + + +def test_parse_changelog_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "changelog": "mussel", + } + path = ChangelogsClient.changelog_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.parse_changelog_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ChangelogsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ChangelogsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder,) + actual = ChangelogsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ChangelogsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization,) + actual = ChangelogsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ChangelogsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project,) + actual = ChangelogsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ChangelogsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = ChangelogsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ChangelogsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.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.ChangelogsTransport, "_prep_wrapped_messages" + ) as prep: + client = ChangelogsClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ChangelogsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ChangelogsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ChangelogsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ChangelogsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = ChangelogsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/tests/unit/gapic/dialogflowcx_v3/test_deployments.py b/tests/unit/gapic/dialogflowcx_v3/test_deployments.py index 86fe33c5..758d5778 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_deployments.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_deployments.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -36,29 +35,12 @@ from google.cloud.dialogflowcx_v3.services.deployments import DeploymentsClient from google.cloud.dialogflowcx_v3.services.deployments import pagers from google.cloud.dialogflowcx_v3.services.deployments import transports -from google.cloud.dialogflowcx_v3.services.deployments.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.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" @@ -206,7 +188,7 @@ def test_deployments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -223,7 +205,7 @@ def test_deployments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -240,7 +222,7 @@ def test_deployments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -269,7 +251,7 @@ def test_deployments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -326,7 +308,7 @@ def test_deployments_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -368,7 +350,7 @@ def test_deployments_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -390,7 +372,7 @@ def test_deployments_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -421,7 +403,7 @@ def test_deployments_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -452,7 +434,7 @@ def test_deployments_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1132,7 +1114,6 @@ def test_deployments_base_transport(): transport.close() -@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( @@ -1156,29 +1137,6 @@ def test_deployments_base_transport_with_credentials_file(): ) -@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_v3.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( @@ -1190,7 +1148,6 @@ def test_deployments_base_transport_with_adc(): 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: @@ -1206,26 +1163,10 @@ def test_deployments_auth_adc(): ) -@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. @@ -1242,26 +1183,6 @@ def test_deployments_transport_auth_adc(transport_class): ) -@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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py b/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py index 6dc9fffc..05e1b1aa 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -36,9 +35,6 @@ from google.cloud.dialogflowcx_v3.services.entity_types import EntityTypesClient from google.cloud.dialogflowcx_v3.services.entity_types import pagers from google.cloud.dialogflowcx_v3.services.entity_types import transports -from google.cloud.dialogflowcx_v3.services.entity_types.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import entity_type from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type from google.oauth2 import service_account @@ -46,20 +42,6 @@ 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" @@ -207,7 +189,7 @@ def test_entity_types_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -224,7 +206,7 @@ def test_entity_types_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -241,7 +223,7 @@ def test_entity_types_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -270,7 +252,7 @@ def test_entity_types_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -327,7 +309,7 @@ def test_entity_types_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -369,7 +351,7 @@ def test_entity_types_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -391,7 +373,7 @@ def test_entity_types_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -422,7 +404,7 @@ def test_entity_types_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -453,7 +435,7 @@ def test_entity_types_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1898,7 +1880,6 @@ def test_entity_types_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_entity_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1922,29 +1903,6 @@ def test_entity_types_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_entity_types_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_v3.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport( - 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_entity_types_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( @@ -1956,7 +1914,6 @@ def test_entity_types_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_entity_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1972,26 +1929,10 @@ def test_entity_types_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_entity_types_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) - EntityTypesClient() - 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.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_entity_types_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2008,26 +1949,6 @@ def test_entity_types_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_entity_types_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_environments.py b/tests/unit/gapic/dialogflowcx_v3/test_environments.py index e395f8b0..4b7b8fd8 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_environments.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_environments.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -39,9 +38,6 @@ from google.cloud.dialogflowcx_v3.services.environments import EnvironmentsClient from google.cloud.dialogflowcx_v3.services.environments import pagers from google.cloud.dialogflowcx_v3.services.environments import transports -from google.cloud.dialogflowcx_v3.services.environments.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import environment from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment from google.longrunning import operations_pb2 @@ -52,20 +48,6 @@ 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" @@ -213,7 +195,7 @@ def test_environments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -230,7 +212,7 @@ def test_environments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -247,7 +229,7 @@ def test_environments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -276,7 +258,7 @@ def test_environments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -333,7 +315,7 @@ def test_environments_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -375,7 +357,7 @@ def test_environments_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -397,7 +379,7 @@ def test_environments_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -428,7 +410,7 @@ def test_environments_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -459,7 +441,7 @@ def test_environments_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2860,7 +2842,6 @@ def test_environments_base_transport(): transport.operations_client -@requires_google_auth_gte_1_25_0 def test_environments_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2884,29 +2865,6 @@ def test_environments_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_environments_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_v3.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - 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_environments_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( @@ -2918,7 +2876,6 @@ def test_environments_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_environments_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2934,21 +2891,6 @@ def test_environments_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_environments_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) - EnvironmentsClient() - 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", [ @@ -2956,7 +2898,6 @@ def test_environments_auth_adc_old_google_auth(): transports.EnvironmentsGrpcAsyncIOTransport, ], ) -@requires_google_auth_gte_1_25_0 def test_environments_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2973,29 +2914,6 @@ def test_environments_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_environments_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_experiments.py b/tests/unit/gapic/dialogflowcx_v3/test_experiments.py index ea724976..fe7a24d5 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_experiments.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_experiments.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -36,9 +35,6 @@ from google.cloud.dialogflowcx_v3.services.experiments import ExperimentsClient from google.cloud.dialogflowcx_v3.services.experiments import pagers from google.cloud.dialogflowcx_v3.services.experiments import transports -from google.cloud.dialogflowcx_v3.services.experiments.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import experiment from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment from google.oauth2 import service_account @@ -48,20 +44,6 @@ 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" @@ -209,7 +191,7 @@ def test_experiments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -226,7 +208,7 @@ def test_experiments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -243,7 +225,7 @@ def test_experiments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -272,7 +254,7 @@ def test_experiments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -329,7 +311,7 @@ def test_experiments_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -371,7 +353,7 @@ def test_experiments_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -393,7 +375,7 @@ def test_experiments_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -424,7 +406,7 @@ def test_experiments_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -455,7 +437,7 @@ def test_experiments_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2272,7 +2254,6 @@ def test_experiments_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_experiments_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2296,29 +2277,6 @@ def test_experiments_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_experiments_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_v3.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExperimentsTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", - ) - - def test_experiments_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( @@ -2330,7 +2288,6 @@ def test_experiments_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_experiments_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2346,26 +2303,10 @@ def test_experiments_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_experiments_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) - ExperimentsClient() - 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.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_experiments_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2382,26 +2323,6 @@ def test_experiments_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_experiments_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_flows.py b/tests/unit/gapic/dialogflowcx_v3/test_flows.py index ddc5814e..720a40bc 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_flows.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_flows.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -39,9 +38,6 @@ from google.cloud.dialogflowcx_v3.services.flows import FlowsClient from google.cloud.dialogflowcx_v3.services.flows import pagers from google.cloud.dialogflowcx_v3.services.flows import transports -from google.cloud.dialogflowcx_v3.services.flows.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import flow from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow from google.cloud.dialogflowcx_v3.types import fulfillment @@ -56,20 +52,6 @@ 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" @@ -204,7 +186,7 @@ def test_flows_client_client_options(client_class, transport_class, transport_na 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -221,7 +203,7 @@ def test_flows_client_client_options(client_class, transport_class, transport_na 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -238,7 +220,7 @@ def test_flows_client_client_options(client_class, transport_class, transport_na 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -267,7 +249,7 @@ def test_flows_client_client_options(client_class, transport_class, transport_na 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -322,7 +304,7 @@ def test_flows_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -364,7 +346,7 @@ def test_flows_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -386,7 +368,7 @@ def test_flows_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -413,7 +395,7 @@ def test_flows_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -440,7 +422,7 @@ def test_flows_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2501,7 +2483,6 @@ def test_flows_base_transport(): transport.operations_client -@requires_google_auth_gte_1_25_0 def test_flows_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2525,29 +2506,6 @@ def test_flows_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_flows_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_v3.services.flows.transports.FlowsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FlowsTransport( - 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_flows_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( @@ -2559,7 +2517,6 @@ def test_flows_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_flows_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2575,26 +2532,10 @@ def test_flows_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_flows_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) - FlowsClient() - 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.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_flows_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2611,26 +2552,6 @@ def test_flows_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_flows_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_intents.py b/tests/unit/gapic/dialogflowcx_v3/test_intents.py index 9685fc3e..36f0ba0f 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_intents.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_intents.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -36,9 +35,6 @@ from google.cloud.dialogflowcx_v3.services.intents import IntentsClient from google.cloud.dialogflowcx_v3.services.intents import pagers from google.cloud.dialogflowcx_v3.services.intents import transports -from google.cloud.dialogflowcx_v3.services.intents.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import intent from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent from google.oauth2 import service_account @@ -46,20 +42,6 @@ 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" @@ -194,7 +176,7 @@ def test_intents_client_client_options(client_class, transport_class, transport_ 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -211,7 +193,7 @@ def test_intents_client_client_options(client_class, transport_class, transport_ 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -228,7 +210,7 @@ def test_intents_client_client_options(client_class, transport_class, transport_ 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -257,7 +239,7 @@ def test_intents_client_client_options(client_class, transport_class, transport_ 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -312,7 +294,7 @@ def test_intents_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -354,7 +336,7 @@ def test_intents_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -376,7 +358,7 @@ def test_intents_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -403,7 +385,7 @@ def test_intents_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -430,7 +412,7 @@ def test_intents_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1723,7 +1705,6 @@ def test_intents_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_intents_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1747,29 +1728,6 @@ def test_intents_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_intents_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_v3.services.intents.transports.IntentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport( - 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_intents_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( @@ -1781,7 +1739,6 @@ def test_intents_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_intents_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1797,26 +1754,10 @@ def test_intents_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_intents_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) - IntentsClient() - 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.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_intents_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1833,26 +1774,6 @@ def test_intents_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_intents_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_pages.py b/tests/unit/gapic/dialogflowcx_v3/test_pages.py index 992d52fd..496244d4 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_pages.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_pages.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -36,9 +35,6 @@ from google.cloud.dialogflowcx_v3.services.pages import PagesClient from google.cloud.dialogflowcx_v3.services.pages import pagers from google.cloud.dialogflowcx_v3.services.pages import transports -from google.cloud.dialogflowcx_v3.services.pages.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import fulfillment from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import page as gcdc_page @@ -49,20 +45,6 @@ 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" @@ -197,7 +179,7 @@ def test_pages_client_client_options(client_class, transport_class, transport_na 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -214,7 +196,7 @@ def test_pages_client_client_options(client_class, transport_class, transport_na 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -231,7 +213,7 @@ def test_pages_client_client_options(client_class, transport_class, transport_na 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -260,7 +242,7 @@ def test_pages_client_client_options(client_class, transport_class, transport_na 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -315,7 +297,7 @@ def test_pages_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -357,7 +339,7 @@ def test_pages_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -379,7 +361,7 @@ def test_pages_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -406,7 +388,7 @@ def test_pages_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -433,7 +415,7 @@ def test_pages_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1684,7 +1666,6 @@ def test_pages_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_pages_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1708,29 +1689,6 @@ def test_pages_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_pages_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_v3.services.pages.transports.PagesTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PagesTransport( - 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_pages_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( @@ -1742,7 +1700,6 @@ def test_pages_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_pages_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1758,26 +1715,10 @@ def test_pages_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_pages_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) - PagesClient() - 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.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_pages_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1794,26 +1735,6 @@ def test_pages_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_pages_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py b/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py index 3eed7d41..c252c4dd 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -40,9 +39,6 @@ ) from google.cloud.dialogflowcx_v3.services.security_settings_service import pagers from google.cloud.dialogflowcx_v3.services.security_settings_service import transports -from google.cloud.dialogflowcx_v3.services.security_settings_service.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import security_settings from google.cloud.dialogflowcx_v3.types import ( security_settings as gcdc_security_settings, @@ -52,20 +48,6 @@ 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" @@ -227,7 +209,7 @@ def test_security_settings_service_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -244,7 +226,7 @@ def test_security_settings_service_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -261,7 +243,7 @@ def test_security_settings_service_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -290,7 +272,7 @@ def test_security_settings_service_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -359,7 +341,7 @@ def test_security_settings_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -401,7 +383,7 @@ def test_security_settings_service_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -423,7 +405,7 @@ def test_security_settings_service_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -458,7 +440,7 @@ def test_security_settings_service_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -493,7 +475,7 @@ def test_security_settings_service_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2134,7 +2116,6 @@ def test_security_settings_service_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_security_settings_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2158,29 +2139,6 @@ def test_security_settings_service_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_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_v3.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecuritySettingsServiceTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", - ) - - def test_security_settings_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( @@ -2192,7 +2150,6 @@ def test_security_settings_service_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_security_settings_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2208,21 +2165,6 @@ def test_security_settings_service_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_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) - SecuritySettingsServiceClient() - 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", [ @@ -2230,7 +2172,6 @@ def test_security_settings_service_auth_adc_old_google_auth(): transports.SecuritySettingsServiceGrpcAsyncIOTransport, ], ) -@requires_google_auth_gte_1_25_0 def test_security_settings_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2247,29 +2188,6 @@ def test_security_settings_service_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecuritySettingsServiceGrpcTransport, - transports.SecuritySettingsServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py b/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py index c4910560..e3e621d4 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -40,9 +39,6 @@ ) from google.cloud.dialogflowcx_v3.services.session_entity_types import pagers from google.cloud.dialogflowcx_v3.services.session_entity_types import transports -from google.cloud.dialogflowcx_v3.services.session_entity_types.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import entity_type from google.cloud.dialogflowcx_v3.types import session_entity_type from google.cloud.dialogflowcx_v3.types import ( @@ -53,20 +49,6 @@ 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" @@ -224,7 +206,7 @@ def test_session_entity_types_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -241,7 +223,7 @@ def test_session_entity_types_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -258,7 +240,7 @@ def test_session_entity_types_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -287,7 +269,7 @@ def test_session_entity_types_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -356,7 +338,7 @@ def test_session_entity_types_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -398,7 +380,7 @@ def test_session_entity_types_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -420,7 +402,7 @@ def test_session_entity_types_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -451,7 +433,7 @@ def test_session_entity_types_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -482,7 +464,7 @@ def test_session_entity_types_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2026,7 +2008,6 @@ def test_session_entity_types_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_session_entity_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2050,29 +2031,6 @@ def test_session_entity_types_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_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_v3.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport( - 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_session_entity_types_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( @@ -2084,7 +2042,6 @@ def test_session_entity_types_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_session_entity_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2100,21 +2057,6 @@ def test_session_entity_types_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_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) - SessionEntityTypesClient() - 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", [ @@ -2122,7 +2064,6 @@ def test_session_entity_types_auth_adc_old_google_auth(): transports.SessionEntityTypesGrpcAsyncIOTransport, ], ) -@requires_google_auth_gte_1_25_0 def test_session_entity_types_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2139,29 +2080,6 @@ def test_session_entity_types_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionEntityTypesGrpcTransport, - transports.SessionEntityTypesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_sessions.py b/tests/unit/gapic/dialogflowcx_v3/test_sessions.py index 7a1a77e8..0a1b0e49 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_sessions.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_sessions.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -35,9 +34,6 @@ from google.cloud.dialogflowcx_v3.services.sessions import SessionsAsyncClient from google.cloud.dialogflowcx_v3.services.sessions import SessionsClient from google.cloud.dialogflowcx_v3.services.sessions import transports -from google.cloud.dialogflowcx_v3.services.sessions.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import audio_config from google.cloud.dialogflowcx_v3.types import entity_type from google.cloud.dialogflowcx_v3.types import intent @@ -50,20 +46,6 @@ 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" @@ -203,7 +185,7 @@ def test_sessions_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -220,7 +202,7 @@ def test_sessions_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -237,7 +219,7 @@ def test_sessions_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -266,7 +248,7 @@ def test_sessions_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -323,7 +305,7 @@ def test_sessions_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -365,7 +347,7 @@ def test_sessions_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -387,7 +369,7 @@ def test_sessions_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -414,7 +396,7 @@ def test_sessions_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -441,7 +423,7 @@ def test_sessions_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1072,7 +1054,6 @@ def test_sessions_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_sessions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1096,29 +1077,6 @@ def test_sessions_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_sessions_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_v3.services.sessions.transports.SessionsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionsTransport( - 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_sessions_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( @@ -1130,7 +1088,6 @@ def test_sessions_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_sessions_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1146,26 +1103,10 @@ def test_sessions_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_sessions_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) - SessionsClient() - 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.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_sessions_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1182,26 +1123,6 @@ def test_sessions_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_sessions_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py b/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py index 2647b4d9..9fdd0312 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -39,9 +38,6 @@ from google.cloud.dialogflowcx_v3.services.test_cases import TestCasesClient from google.cloud.dialogflowcx_v3.services.test_cases import pagers from google.cloud.dialogflowcx_v3.services.test_cases import transports -from google.cloud.dialogflowcx_v3.services.test_cases.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import audio_config from google.cloud.dialogflowcx_v3.types import fulfillment from google.cloud.dialogflowcx_v3.types import intent @@ -60,20 +56,6 @@ 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" @@ -219,7 +201,7 @@ def test_test_cases_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -236,7 +218,7 @@ def test_test_cases_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -253,7 +235,7 @@ def test_test_cases_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -282,7 +264,7 @@ def test_test_cases_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -339,7 +321,7 @@ def test_test_cases_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -381,7 +363,7 @@ def test_test_cases_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -403,7 +385,7 @@ def test_test_cases_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -434,7 +416,7 @@ def test_test_cases_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -465,7 +447,7 @@ def test_test_cases_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -3111,7 +3093,6 @@ def test_test_cases_base_transport(): transport.operations_client -@requires_google_auth_gte_1_25_0 def test_test_cases_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -3135,29 +3116,6 @@ def test_test_cases_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_test_cases_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_v3.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TestCasesTransport( - 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_test_cases_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( @@ -3169,7 +3127,6 @@ def test_test_cases_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_test_cases_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -3185,26 +3142,10 @@ def test_test_cases_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_test_cases_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) - TestCasesClient() - 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.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_test_cases_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -3221,26 +3162,6 @@ def test_test_cases_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_test_cases_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py b/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py index c5f97e0a..5c13ca0b 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -40,9 +39,6 @@ ) from google.cloud.dialogflowcx_v3.services.transition_route_groups import pagers from google.cloud.dialogflowcx_v3.services.transition_route_groups import transports -from google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import fulfillment from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import response_message @@ -56,20 +52,6 @@ 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" @@ -231,7 +213,7 @@ def test_transition_route_groups_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -248,7 +230,7 @@ def test_transition_route_groups_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -265,7 +247,7 @@ def test_transition_route_groups_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -294,7 +276,7 @@ def test_transition_route_groups_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -363,7 +345,7 @@ def test_transition_route_groups_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -405,7 +387,7 @@ def test_transition_route_groups_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -427,7 +409,7 @@ def test_transition_route_groups_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -462,7 +444,7 @@ def test_transition_route_groups_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -497,7 +479,7 @@ def test_transition_route_groups_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2048,7 +2030,6 @@ def test_transition_route_groups_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_transition_route_groups_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2072,29 +2053,6 @@ def test_transition_route_groups_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_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_v3.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TransitionRouteGroupsTransport( - 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_transition_route_groups_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( @@ -2106,7 +2064,6 @@ def test_transition_route_groups_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_transition_route_groups_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2122,21 +2079,6 @@ def test_transition_route_groups_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_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) - TransitionRouteGroupsClient() - 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", [ @@ -2144,7 +2086,6 @@ def test_transition_route_groups_auth_adc_old_google_auth(): transports.TransitionRouteGroupsGrpcAsyncIOTransport, ], ) -@requires_google_auth_gte_1_25_0 def test_transition_route_groups_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2161,29 +2102,6 @@ def test_transition_route_groups_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.TransitionRouteGroupsGrpcTransport, - transports.TransitionRouteGroupsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_versions.py b/tests/unit/gapic/dialogflowcx_v3/test_versions.py index 99400e75..54b6f9c3 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_versions.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_versions.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -39,9 +38,6 @@ from google.cloud.dialogflowcx_v3.services.versions import VersionsClient from google.cloud.dialogflowcx_v3.services.versions import pagers from google.cloud.dialogflowcx_v3.services.versions import transports -from google.cloud.dialogflowcx_v3.services.versions.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import flow from google.cloud.dialogflowcx_v3.types import version from google.cloud.dialogflowcx_v3.types import version as gcdc_version @@ -53,20 +49,6 @@ 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" @@ -206,7 +188,7 @@ def test_versions_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -223,7 +205,7 @@ def test_versions_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -240,7 +222,7 @@ def test_versions_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -269,7 +251,7 @@ def test_versions_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -326,7 +308,7 @@ def test_versions_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -368,7 +350,7 @@ def test_versions_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -390,7 +372,7 @@ def test_versions_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -417,7 +399,7 @@ def test_versions_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -444,7 +426,7 @@ def test_versions_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1927,7 +1909,6 @@ def test_versions_base_transport(): transport.operations_client -@requires_google_auth_gte_1_25_0 def test_versions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1951,29 +1932,6 @@ def test_versions_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_versions_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_v3.services.versions.transports.VersionsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VersionsTransport( - 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_versions_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( @@ -1985,7 +1943,6 @@ def test_versions_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_versions_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2001,26 +1958,10 @@ def test_versions_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_versions_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) - VersionsClient() - 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.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_versions_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2037,26 +1978,6 @@ def test_versions_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_versions_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py b/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py index cf38448d..3f684022 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -36,9 +35,6 @@ from google.cloud.dialogflowcx_v3.services.webhooks import WebhooksClient from google.cloud.dialogflowcx_v3.services.webhooks import pagers from google.cloud.dialogflowcx_v3.services.webhooks import transports -from google.cloud.dialogflowcx_v3.services.webhooks.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3.types import webhook from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook from google.oauth2 import service_account @@ -47,20 +43,6 @@ 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" @@ -200,7 +182,7 @@ def test_webhooks_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -217,7 +199,7 @@ def test_webhooks_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -234,7 +216,7 @@ def test_webhooks_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -263,7 +245,7 @@ def test_webhooks_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -320,7 +302,7 @@ def test_webhooks_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -362,7 +344,7 @@ def test_webhooks_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -384,7 +366,7 @@ def test_webhooks_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -411,7 +393,7 @@ def test_webhooks_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -438,7 +420,7 @@ def test_webhooks_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1726,7 +1708,6 @@ def test_webhooks_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_webhooks_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1750,29 +1731,6 @@ def test_webhooks_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_webhooks_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_v3.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebhooksTransport( - 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_webhooks_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( @@ -1784,7 +1742,6 @@ def test_webhooks_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_webhooks_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1800,26 +1757,10 @@ def test_webhooks_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_webhooks_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) - WebhooksClient() - 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.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_webhooks_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1836,26 +1777,6 @@ def test_webhooks_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_webhooks_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py index b3613786..58f48644 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -39,9 +38,6 @@ from google.cloud.dialogflowcx_v3beta1.services.agents import AgentsClient from google.cloud.dialogflowcx_v3beta1.services.agents import pagers from google.cloud.dialogflowcx_v3beta1.services.agents import transports -from google.cloud.dialogflowcx_v3beta1.services.agents.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import advanced_settings from google.cloud.dialogflowcx_v3beta1.types import agent from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent @@ -53,20 +49,6 @@ 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" @@ -201,7 +183,7 @@ def test_agents_client_client_options(client_class, transport_class, transport_n 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -218,7 +200,7 @@ def test_agents_client_client_options(client_class, transport_class, transport_n 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -235,7 +217,7 @@ def test_agents_client_client_options(client_class, transport_class, transport_n 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -264,7 +246,7 @@ def test_agents_client_client_options(client_class, transport_class, transport_n 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -319,7 +301,7 @@ def test_agents_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -361,7 +343,7 @@ def test_agents_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -383,7 +365,7 @@ def test_agents_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -410,7 +392,7 @@ def test_agents_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -437,7 +419,7 @@ def test_agents_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2399,7 +2381,6 @@ def test_agents_base_transport(): transport.operations_client -@requires_google_auth_gte_1_25_0 def test_agents_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2423,29 +2404,6 @@ def test_agents_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_agents_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.agents.transports.AgentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport( - 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_agents_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( @@ -2457,7 +2415,6 @@ def test_agents_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_agents_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2473,26 +2430,10 @@ def test_agents_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_agents_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) - AgentsClient() - 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.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_agents_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2509,26 +2450,6 @@ def test_agents_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_agents_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_changelogs.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_changelogs.py new file mode 100644 index 00000000..af4f74bd --- /dev/null +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_changelogs.py @@ -0,0 +1,1596 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflowcx_v3beta1.services.changelogs import ChangelogsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.changelogs import ChangelogsClient +from google.cloud.dialogflowcx_v3beta1.services.changelogs import pagers +from google.cloud.dialogflowcx_v3beta1.services.changelogs import transports +from google.cloud.dialogflowcx_v3beta1.types import changelog +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ChangelogsClient._get_default_mtls_endpoint(None) is None + assert ( + ChangelogsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + ChangelogsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ChangelogsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ChangelogsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ChangelogsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ChangelogsClient, ChangelogsAsyncClient,]) +def test_changelogs_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.ChangelogsGrpcTransport, "grpc"), + (transports.ChangelogsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_changelogs_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", [ChangelogsClient, ChangelogsAsyncClient,]) +def test_changelogs_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_changelogs_client_get_transport_class(): + transport = ChangelogsClient.get_transport_class() + available_transports = [ + transports.ChangelogsGrpcTransport, + ] + assert transport in available_transports + + transport = ChangelogsClient.get_transport_class("grpc") + assert transport == transports.ChangelogsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ChangelogsClient, transports.ChangelogsGrpcTransport, "grpc"), + ( + ChangelogsAsyncClient, + transports.ChangelogsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ChangelogsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ChangelogsClient) +) +@mock.patch.object( + ChangelogsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ChangelogsAsyncClient), +) +def test_changelogs_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(ChangelogsClient, "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(ChangelogsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, 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", + [ + (ChangelogsClient, transports.ChangelogsGrpcTransport, "grpc", "true"), + ( + ChangelogsAsyncClient, + transports.ChangelogsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ChangelogsClient, transports.ChangelogsGrpcTransport, "grpc", "false"), + ( + ChangelogsAsyncClient, + transports.ChangelogsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ChangelogsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ChangelogsClient) +) +@mock.patch.object( + ChangelogsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ChangelogsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_changelogs_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(transport=transport_name, 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ChangelogsClient, transports.ChangelogsGrpcTransport, "grpc"), + ( + ChangelogsAsyncClient, + transports.ChangelogsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_changelogs_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(transport=transport_name, 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", + [ + (ChangelogsClient, transports.ChangelogsGrpcTransport, "grpc"), + ( + ChangelogsAsyncClient, + transports.ChangelogsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_changelogs_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(transport=transport_name, 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_changelogs_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.changelogs.transports.ChangelogsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ChangelogsClient(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_changelogs( + transport: str = "grpc", request_type=changelog.ListChangelogsRequest +): + client = ChangelogsClient( + 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_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.ListChangelogsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.ListChangelogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChangelogsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_changelogs_from_dict(): + test_list_changelogs(request_type=dict) + + +def test_list_changelogs_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 = ChangelogsClient( + 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_changelogs), "__call__") as call: + client.list_changelogs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.ListChangelogsRequest() + + +@pytest.mark.asyncio +async def test_list_changelogs_async( + transport: str = "grpc_asyncio", request_type=changelog.ListChangelogsRequest +): + client = ChangelogsAsyncClient( + 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_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + changelog.ListChangelogsResponse(next_page_token="next_page_token_value",) + ) + response = await client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.ListChangelogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChangelogsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_changelogs_async_from_dict(): + await test_list_changelogs_async(request_type=dict) + + +def test_list_changelogs_field_headers(): + client = ChangelogsClient(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 = changelog.ListChangelogsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + call.return_value = changelog.ListChangelogsResponse() + client.list_changelogs(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_changelogs_field_headers_async(): + client = ChangelogsAsyncClient(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 = changelog.ListChangelogsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + changelog.ListChangelogsResponse() + ) + await client.list_changelogs(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_changelogs_flattened(): + client = ChangelogsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.ListChangelogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_changelogs(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_changelogs_flattened_error(): + client = ChangelogsClient(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_changelogs( + changelog.ListChangelogsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_changelogs_flattened_async(): + client = ChangelogsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.ListChangelogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + changelog.ListChangelogsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_changelogs(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_changelogs_flattened_error_async(): + client = ChangelogsAsyncClient(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_changelogs( + changelog.ListChangelogsRequest(), parent="parent_value", + ) + + +def test_list_changelogs_pager(): + client = ChangelogsClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + changelog.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + changelog.ListChangelogsResponse(changelogs=[], next_page_token="def",), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(),], next_page_token="ghi", + ), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(), changelog.Changelog(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_changelogs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, changelog.Changelog) for i in results) + + +def test_list_changelogs_pages(): + client = ChangelogsClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + changelog.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + changelog.ListChangelogsResponse(changelogs=[], next_page_token="def",), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(),], next_page_token="ghi", + ), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(), changelog.Changelog(),], + ), + RuntimeError, + ) + pages = list(client.list_changelogs(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_changelogs_async_pager(): + client = ChangelogsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_changelogs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + changelog.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + changelog.ListChangelogsResponse(changelogs=[], next_page_token="def",), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(),], next_page_token="ghi", + ), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(), changelog.Changelog(),], + ), + RuntimeError, + ) + async_pager = await client.list_changelogs(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, changelog.Changelog) for i in responses) + + +@pytest.mark.asyncio +async def test_list_changelogs_async_pages(): + client = ChangelogsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_changelogs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + changelog.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + changelog.ListChangelogsResponse(changelogs=[], next_page_token="def",), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(),], next_page_token="ghi", + ), + changelog.ListChangelogsResponse( + changelogs=[changelog.Changelog(), changelog.Changelog(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_changelogs(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_changelog( + transport: str = "grpc", request_type=changelog.GetChangelogRequest +): + client = ChangelogsClient( + 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_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.Changelog( + name="name_value", + user_email="user_email_value", + display_name="display_name_value", + action="action_value", + type_="type__value", + resource="resource_value", + ) + response = client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.GetChangelogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, changelog.Changelog) + assert response.name == "name_value" + assert response.user_email == "user_email_value" + assert response.display_name == "display_name_value" + assert response.action == "action_value" + assert response.type_ == "type__value" + assert response.resource == "resource_value" + + +def test_get_changelog_from_dict(): + test_get_changelog(request_type=dict) + + +def test_get_changelog_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 = ChangelogsClient( + 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_changelog), "__call__") as call: + client.get_changelog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.GetChangelogRequest() + + +@pytest.mark.asyncio +async def test_get_changelog_async( + transport: str = "grpc_asyncio", request_type=changelog.GetChangelogRequest +): + client = ChangelogsAsyncClient( + 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_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + changelog.Changelog( + name="name_value", + user_email="user_email_value", + display_name="display_name_value", + action="action_value", + type_="type__value", + resource="resource_value", + ) + ) + response = await client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == changelog.GetChangelogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, changelog.Changelog) + assert response.name == "name_value" + assert response.user_email == "user_email_value" + assert response.display_name == "display_name_value" + assert response.action == "action_value" + assert response.type_ == "type__value" + assert response.resource == "resource_value" + + +@pytest.mark.asyncio +async def test_get_changelog_async_from_dict(): + await test_get_changelog_async(request_type=dict) + + +def test_get_changelog_field_headers(): + client = ChangelogsClient(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 = changelog.GetChangelogRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + call.return_value = changelog.Changelog() + client.get_changelog(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_changelog_field_headers_async(): + client = ChangelogsAsyncClient(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 = changelog.GetChangelogRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(changelog.Changelog()) + await client.get_changelog(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_changelog_flattened(): + client = ChangelogsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.Changelog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_changelog(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_changelog_flattened_error(): + client = ChangelogsClient(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_changelog( + changelog.GetChangelogRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_changelog_flattened_async(): + client = ChangelogsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.Changelog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(changelog.Changelog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_changelog(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_changelog_flattened_error_async(): + client = ChangelogsAsyncClient(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_changelog( + changelog.GetChangelogRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ChangelogsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChangelogsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ChangelogsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChangelogsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ChangelogsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChangelogsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChangelogsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ChangelogsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChangelogsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ChangelogsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [transports.ChangelogsGrpcTransport, transports.ChangelogsGrpcAsyncIOTransport,], +) +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 = ChangelogsClient(credentials=ga_credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.ChangelogsGrpcTransport,) + + +def test_changelogs_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ChangelogsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_changelogs_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflowcx_v3beta1.services.changelogs.transports.ChangelogsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ChangelogsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_changelogs", + "get_changelog", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_changelogs_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.changelogs.transports.ChangelogsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ChangelogsTransport( + 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", + ) + + +def test_changelogs_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.changelogs.transports.ChangelogsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ChangelogsTransport() + adc.assert_called_once() + + +def test_changelogs_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) + ChangelogsClient() + 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, + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.ChangelogsGrpcTransport, transports.ChangelogsGrpcAsyncIOTransport,], +) +def test_changelogs_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,grpc_helpers", + [ + (transports.ChangelogsGrpcTransport, grpc_helpers), + (transports.ChangelogsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_changelogs_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.ChangelogsGrpcTransport, transports.ChangelogsGrpcAsyncIOTransport], +) +def test_changelogs_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_changelogs_host_no_port(): + client = ChangelogsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_changelogs_host_with_port(): + client = ChangelogsClient( + 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_changelogs_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ChangelogsGrpcTransport( + 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_changelogs_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ChangelogsGrpcAsyncIOTransport( + 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.ChangelogsGrpcTransport, transports.ChangelogsGrpcAsyncIOTransport], +) +def test_changelogs_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.ChangelogsGrpcTransport, transports.ChangelogsGrpcAsyncIOTransport], +) +def test_changelogs_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_changelog_path(): + project = "squid" + location = "clam" + agent = "whelk" + changelog = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}".format( + project=project, location=location, agent=agent, changelog=changelog, + ) + actual = ChangelogsClient.changelog_path(project, location, agent, changelog) + assert expected == actual + + +def test_parse_changelog_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "changelog": "mussel", + } + path = ChangelogsClient.changelog_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.parse_changelog_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ChangelogsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ChangelogsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder,) + actual = ChangelogsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ChangelogsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization,) + actual = ChangelogsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ChangelogsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project,) + actual = ChangelogsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ChangelogsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = ChangelogsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ChangelogsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ChangelogsClient.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.ChangelogsTransport, "_prep_wrapped_messages" + ) as prep: + client = ChangelogsClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ChangelogsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ChangelogsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ChangelogsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ChangelogsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = ChangelogsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py index bd25eab6..262e96c4 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -38,29 +37,12 @@ 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" @@ -208,7 +190,7 @@ def test_deployments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -225,7 +207,7 @@ def test_deployments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -242,7 +224,7 @@ def test_deployments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -271,7 +253,7 @@ def test_deployments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -328,7 +310,7 @@ def test_deployments_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -370,7 +352,7 @@ def test_deployments_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -392,7 +374,7 @@ def test_deployments_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -423,7 +405,7 @@ def test_deployments_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -454,7 +436,7 @@ def test_deployments_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1134,7 +1116,6 @@ def test_deployments_base_transport(): transport.close() -@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( @@ -1158,29 +1139,6 @@ def test_deployments_base_transport_with_credentials_file(): ) -@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( @@ -1192,7 +1150,6 @@ def test_deployments_base_transport_with_adc(): 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: @@ -1208,26 +1165,10 @@ def test_deployments_auth_adc(): ) -@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. @@ -1244,26 +1185,6 @@ def test_deployments_transport_auth_adc(transport_class): ) -@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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py index 25858e0f..f56acd5a 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -38,9 +37,6 @@ from google.cloud.dialogflowcx_v3beta1.services.entity_types import EntityTypesClient from google.cloud.dialogflowcx_v3beta1.services.entity_types import pagers from google.cloud.dialogflowcx_v3beta1.services.entity_types import transports -from google.cloud.dialogflowcx_v3beta1.services.entity_types.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import entity_type from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type from google.oauth2 import service_account @@ -48,20 +44,6 @@ 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" @@ -209,7 +191,7 @@ def test_entity_types_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -226,7 +208,7 @@ def test_entity_types_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -243,7 +225,7 @@ def test_entity_types_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -272,7 +254,7 @@ def test_entity_types_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -329,7 +311,7 @@ def test_entity_types_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -371,7 +353,7 @@ def test_entity_types_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -393,7 +375,7 @@ def test_entity_types_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -424,7 +406,7 @@ def test_entity_types_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -455,7 +437,7 @@ def test_entity_types_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1900,7 +1882,6 @@ def test_entity_types_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_entity_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1924,29 +1905,6 @@ def test_entity_types_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_entity_types_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.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport( - 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_entity_types_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( @@ -1958,7 +1916,6 @@ def test_entity_types_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_entity_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1974,26 +1931,10 @@ def test_entity_types_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_entity_types_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) - EntityTypesClient() - 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.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_entity_types_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2010,26 +1951,6 @@ def test_entity_types_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_entity_types_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py index dd5441a6..633682c0 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -41,9 +40,6 @@ from google.cloud.dialogflowcx_v3beta1.services.environments import EnvironmentsClient from google.cloud.dialogflowcx_v3beta1.services.environments import pagers from google.cloud.dialogflowcx_v3beta1.services.environments import transports -from google.cloud.dialogflowcx_v3beta1.services.environments.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import environment from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment from google.longrunning import operations_pb2 @@ -54,20 +50,6 @@ 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" @@ -215,7 +197,7 @@ def test_environments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -232,7 +214,7 @@ def test_environments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -249,7 +231,7 @@ def test_environments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -278,7 +260,7 @@ def test_environments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -335,7 +317,7 @@ def test_environments_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -377,7 +359,7 @@ def test_environments_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -399,7 +381,7 @@ def test_environments_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -430,7 +412,7 @@ def test_environments_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -461,7 +443,7 @@ def test_environments_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2862,7 +2844,6 @@ def test_environments_base_transport(): transport.operations_client -@requires_google_auth_gte_1_25_0 def test_environments_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2886,29 +2867,6 @@ def test_environments_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_environments_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.environments.transports.EnvironmentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - 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_environments_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( @@ -2920,7 +2878,6 @@ def test_environments_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_environments_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2936,21 +2893,6 @@ def test_environments_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_environments_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) - EnvironmentsClient() - 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", [ @@ -2958,7 +2900,6 @@ def test_environments_auth_adc_old_google_auth(): transports.EnvironmentsGrpcAsyncIOTransport, ], ) -@requires_google_auth_gte_1_25_0 def test_environments_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2975,29 +2916,6 @@ def test_environments_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_environments_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py index d82ef6f8..3e6950b6 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -38,9 +37,6 @@ from google.cloud.dialogflowcx_v3beta1.services.experiments import ExperimentsClient from google.cloud.dialogflowcx_v3beta1.services.experiments import pagers from google.cloud.dialogflowcx_v3beta1.services.experiments import transports -from google.cloud.dialogflowcx_v3beta1.services.experiments.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import experiment from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment from google.oauth2 import service_account @@ -50,20 +46,6 @@ 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" @@ -211,7 +193,7 @@ def test_experiments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -228,7 +210,7 @@ def test_experiments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -245,7 +227,7 @@ def test_experiments_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -274,7 +256,7 @@ def test_experiments_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -331,7 +313,7 @@ def test_experiments_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -373,7 +355,7 @@ def test_experiments_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -395,7 +377,7 @@ def test_experiments_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -426,7 +408,7 @@ def test_experiments_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -457,7 +439,7 @@ def test_experiments_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2274,7 +2256,6 @@ def test_experiments_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_experiments_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2298,29 +2279,6 @@ def test_experiments_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_experiments_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.experiments.transports.ExperimentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExperimentsTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", - ) - - def test_experiments_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( @@ -2332,7 +2290,6 @@ def test_experiments_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_experiments_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2348,26 +2305,10 @@ def test_experiments_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_experiments_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) - ExperimentsClient() - 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.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_experiments_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2384,26 +2325,6 @@ def test_experiments_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_experiments_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py index 86c41ff7..2dd5cad9 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -39,9 +38,6 @@ from google.cloud.dialogflowcx_v3beta1.services.flows import FlowsClient from google.cloud.dialogflowcx_v3beta1.services.flows import pagers from google.cloud.dialogflowcx_v3beta1.services.flows import transports -from google.cloud.dialogflowcx_v3beta1.services.flows.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import flow from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow from google.cloud.dialogflowcx_v3beta1.types import fulfillment @@ -56,20 +52,6 @@ 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" @@ -204,7 +186,7 @@ def test_flows_client_client_options(client_class, transport_class, transport_na 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -221,7 +203,7 @@ def test_flows_client_client_options(client_class, transport_class, transport_na 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -238,7 +220,7 @@ def test_flows_client_client_options(client_class, transport_class, transport_na 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -267,7 +249,7 @@ def test_flows_client_client_options(client_class, transport_class, transport_na 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -322,7 +304,7 @@ def test_flows_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -364,7 +346,7 @@ def test_flows_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -386,7 +368,7 @@ def test_flows_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -413,7 +395,7 @@ def test_flows_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -440,7 +422,7 @@ def test_flows_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2501,7 +2483,6 @@ def test_flows_base_transport(): transport.operations_client -@requires_google_auth_gte_1_25_0 def test_flows_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2525,29 +2506,6 @@ def test_flows_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_flows_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.flows.transports.FlowsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FlowsTransport( - 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_flows_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( @@ -2559,7 +2517,6 @@ def test_flows_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_flows_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2575,26 +2532,10 @@ def test_flows_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_flows_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) - FlowsClient() - 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.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_flows_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2611,26 +2552,6 @@ def test_flows_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_flows_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py index e4d37f11..d6ab7244 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -36,9 +35,6 @@ from google.cloud.dialogflowcx_v3beta1.services.intents import IntentsClient from google.cloud.dialogflowcx_v3beta1.services.intents import pagers from google.cloud.dialogflowcx_v3beta1.services.intents import transports -from google.cloud.dialogflowcx_v3beta1.services.intents.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import intent from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent from google.oauth2 import service_account @@ -46,20 +42,6 @@ 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" @@ -194,7 +176,7 @@ def test_intents_client_client_options(client_class, transport_class, transport_ 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -211,7 +193,7 @@ def test_intents_client_client_options(client_class, transport_class, transport_ 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -228,7 +210,7 @@ def test_intents_client_client_options(client_class, transport_class, transport_ 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -257,7 +239,7 @@ def test_intents_client_client_options(client_class, transport_class, transport_ 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -312,7 +294,7 @@ def test_intents_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -354,7 +336,7 @@ def test_intents_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -376,7 +358,7 @@ def test_intents_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -403,7 +385,7 @@ def test_intents_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -430,7 +412,7 @@ def test_intents_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1723,7 +1705,6 @@ def test_intents_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_intents_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1747,29 +1728,6 @@ def test_intents_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_intents_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.intents.transports.IntentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport( - 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_intents_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( @@ -1781,7 +1739,6 @@ def test_intents_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_intents_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1797,26 +1754,10 @@ def test_intents_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_intents_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) - IntentsClient() - 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.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_intents_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1833,26 +1774,6 @@ def test_intents_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_intents_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py index d591070d..f64b94f6 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -36,9 +35,6 @@ from google.cloud.dialogflowcx_v3beta1.services.pages import PagesClient from google.cloud.dialogflowcx_v3beta1.services.pages import pagers from google.cloud.dialogflowcx_v3beta1.services.pages import transports -from google.cloud.dialogflowcx_v3beta1.services.pages.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import fulfillment from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page @@ -49,20 +45,6 @@ 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" @@ -197,7 +179,7 @@ def test_pages_client_client_options(client_class, transport_class, transport_na 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -214,7 +196,7 @@ def test_pages_client_client_options(client_class, transport_class, transport_na 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -231,7 +213,7 @@ def test_pages_client_client_options(client_class, transport_class, transport_na 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -260,7 +242,7 @@ def test_pages_client_client_options(client_class, transport_class, transport_na 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -315,7 +297,7 @@ def test_pages_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -357,7 +339,7 @@ def test_pages_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -379,7 +361,7 @@ def test_pages_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -406,7 +388,7 @@ def test_pages_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -433,7 +415,7 @@ def test_pages_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1684,7 +1666,6 @@ def test_pages_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_pages_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1708,29 +1689,6 @@ def test_pages_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_pages_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.pages.transports.PagesTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PagesTransport( - 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_pages_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( @@ -1742,7 +1700,6 @@ def test_pages_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_pages_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1758,26 +1715,10 @@ def test_pages_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_pages_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) - PagesClient() - 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.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_pages_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1794,26 +1735,6 @@ def test_pages_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_pages_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py index 299276ac..b310528f 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -42,9 +41,6 @@ from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import ( transports, ) -from google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import security_settings from google.cloud.dialogflowcx_v3beta1.types import ( security_settings as gcdc_security_settings, @@ -54,20 +50,6 @@ 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" @@ -229,7 +211,7 @@ def test_security_settings_service_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -246,7 +228,7 @@ def test_security_settings_service_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -263,7 +245,7 @@ def test_security_settings_service_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -292,7 +274,7 @@ def test_security_settings_service_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -361,7 +343,7 @@ def test_security_settings_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -403,7 +385,7 @@ def test_security_settings_service_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -425,7 +407,7 @@ def test_security_settings_service_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -460,7 +442,7 @@ def test_security_settings_service_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -495,7 +477,7 @@ def test_security_settings_service_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2136,7 +2118,6 @@ def test_security_settings_service_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_security_settings_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2160,29 +2141,6 @@ def test_security_settings_service_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_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.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecuritySettingsServiceTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", - ) - - def test_security_settings_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( @@ -2194,7 +2152,6 @@ def test_security_settings_service_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_security_settings_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2210,21 +2167,6 @@ def test_security_settings_service_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_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) - SecuritySettingsServiceClient() - 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", [ @@ -2232,7 +2174,6 @@ def test_security_settings_service_auth_adc_old_google_auth(): transports.SecuritySettingsServiceGrpcAsyncIOTransport, ], ) -@requires_google_auth_gte_1_25_0 def test_security_settings_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2249,29 +2190,6 @@ def test_security_settings_service_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecuritySettingsServiceGrpcTransport, - transports.SecuritySettingsServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py index 94cb2efd..58e81b5e 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -40,9 +39,6 @@ ) from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import pagers from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import transports -from google.cloud.dialogflowcx_v3beta1.services.session_entity_types.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import entity_type from google.cloud.dialogflowcx_v3beta1.types import session_entity_type from google.cloud.dialogflowcx_v3beta1.types import ( @@ -53,20 +49,6 @@ 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" @@ -224,7 +206,7 @@ def test_session_entity_types_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -241,7 +223,7 @@ def test_session_entity_types_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -258,7 +240,7 @@ def test_session_entity_types_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -287,7 +269,7 @@ def test_session_entity_types_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -356,7 +338,7 @@ def test_session_entity_types_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -398,7 +380,7 @@ def test_session_entity_types_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -420,7 +402,7 @@ def test_session_entity_types_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -451,7 +433,7 @@ def test_session_entity_types_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -482,7 +464,7 @@ def test_session_entity_types_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2026,7 +2008,6 @@ def test_session_entity_types_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_session_entity_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2050,29 +2031,6 @@ def test_session_entity_types_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_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.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport( - 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_session_entity_types_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( @@ -2084,7 +2042,6 @@ def test_session_entity_types_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_session_entity_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2100,21 +2057,6 @@ def test_session_entity_types_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_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) - SessionEntityTypesClient() - 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", [ @@ -2122,7 +2064,6 @@ def test_session_entity_types_auth_adc_old_google_auth(): transports.SessionEntityTypesGrpcAsyncIOTransport, ], ) -@requires_google_auth_gte_1_25_0 def test_session_entity_types_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2139,29 +2080,6 @@ def test_session_entity_types_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionEntityTypesGrpcTransport, - transports.SessionEntityTypesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py index d8f9720d..bc616623 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -35,9 +34,6 @@ from google.cloud.dialogflowcx_v3beta1.services.sessions import SessionsAsyncClient from google.cloud.dialogflowcx_v3beta1.services.sessions import SessionsClient from google.cloud.dialogflowcx_v3beta1.services.sessions import transports -from google.cloud.dialogflowcx_v3beta1.services.sessions.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import audio_config from google.cloud.dialogflowcx_v3beta1.types import entity_type from google.cloud.dialogflowcx_v3beta1.types import intent @@ -50,20 +46,6 @@ 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" @@ -203,7 +185,7 @@ def test_sessions_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -220,7 +202,7 @@ def test_sessions_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -237,7 +219,7 @@ def test_sessions_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -266,7 +248,7 @@ def test_sessions_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -323,7 +305,7 @@ def test_sessions_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -365,7 +347,7 @@ def test_sessions_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -387,7 +369,7 @@ def test_sessions_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -414,7 +396,7 @@ def test_sessions_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -441,7 +423,7 @@ def test_sessions_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1072,7 +1054,6 @@ def test_sessions_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_sessions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1096,29 +1077,6 @@ def test_sessions_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_sessions_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.sessions.transports.SessionsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionsTransport( - 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_sessions_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( @@ -1130,7 +1088,6 @@ def test_sessions_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_sessions_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1146,26 +1103,10 @@ def test_sessions_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_sessions_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) - SessionsClient() - 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.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_sessions_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1182,26 +1123,6 @@ def test_sessions_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_sessions_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py index 8b1c7b6d..a30ca8c5 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -39,9 +38,6 @@ from google.cloud.dialogflowcx_v3beta1.services.test_cases import TestCasesClient from google.cloud.dialogflowcx_v3beta1.services.test_cases import pagers from google.cloud.dialogflowcx_v3beta1.services.test_cases import transports -from google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import audio_config from google.cloud.dialogflowcx_v3beta1.types import fulfillment from google.cloud.dialogflowcx_v3beta1.types import intent @@ -60,20 +56,6 @@ 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" @@ -219,7 +201,7 @@ def test_test_cases_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -236,7 +218,7 @@ def test_test_cases_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -253,7 +235,7 @@ def test_test_cases_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -282,7 +264,7 @@ def test_test_cases_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -339,7 +321,7 @@ def test_test_cases_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -381,7 +363,7 @@ def test_test_cases_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -403,7 +385,7 @@ def test_test_cases_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -434,7 +416,7 @@ def test_test_cases_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -465,7 +447,7 @@ def test_test_cases_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -3111,7 +3093,6 @@ def test_test_cases_base_transport(): transport.operations_client -@requires_google_auth_gte_1_25_0 def test_test_cases_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -3135,29 +3116,6 @@ def test_test_cases_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_test_cases_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.test_cases.transports.TestCasesTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TestCasesTransport( - 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_test_cases_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( @@ -3169,7 +3127,6 @@ def test_test_cases_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_test_cases_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -3185,26 +3142,10 @@ def test_test_cases_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_test_cases_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) - TestCasesClient() - 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.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_test_cases_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -3221,26 +3162,6 @@ def test_test_cases_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_test_cases_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py index 481dd907..f042702b 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -42,9 +41,6 @@ from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import ( transports, ) -from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import fulfillment from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import response_message @@ -58,20 +54,6 @@ 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" @@ -233,7 +215,7 @@ def test_transition_route_groups_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -250,7 +232,7 @@ def test_transition_route_groups_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -267,7 +249,7 @@ def test_transition_route_groups_client_client_options( 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -296,7 +278,7 @@ def test_transition_route_groups_client_client_options( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -365,7 +347,7 @@ def test_transition_route_groups_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -407,7 +389,7 @@ def test_transition_route_groups_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -429,7 +411,7 @@ def test_transition_route_groups_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -464,7 +446,7 @@ def test_transition_route_groups_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -499,7 +481,7 @@ def test_transition_route_groups_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -2050,7 +2032,6 @@ def test_transition_route_groups_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_transition_route_groups_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -2074,29 +2055,6 @@ def test_transition_route_groups_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_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.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TransitionRouteGroupsTransport( - 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_transition_route_groups_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( @@ -2108,7 +2066,6 @@ def test_transition_route_groups_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_transition_route_groups_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2124,21 +2081,6 @@ def test_transition_route_groups_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_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) - TransitionRouteGroupsClient() - 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", [ @@ -2146,7 +2088,6 @@ def test_transition_route_groups_auth_adc_old_google_auth(): transports.TransitionRouteGroupsGrpcAsyncIOTransport, ], ) -@requires_google_auth_gte_1_25_0 def test_transition_route_groups_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2163,29 +2104,6 @@ def test_transition_route_groups_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.TransitionRouteGroupsGrpcTransport, - transports.TransitionRouteGroupsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py index 2c366f33..679b1e7e 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -39,9 +38,6 @@ from google.cloud.dialogflowcx_v3beta1.services.versions import VersionsClient from google.cloud.dialogflowcx_v3beta1.services.versions import pagers from google.cloud.dialogflowcx_v3beta1.services.versions import transports -from google.cloud.dialogflowcx_v3beta1.services.versions.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import flow from google.cloud.dialogflowcx_v3beta1.types import version from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version @@ -53,20 +49,6 @@ 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" @@ -206,7 +188,7 @@ def test_versions_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -223,7 +205,7 @@ def test_versions_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -240,7 +222,7 @@ def test_versions_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -269,7 +251,7 @@ def test_versions_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -326,7 +308,7 @@ def test_versions_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -368,7 +350,7 @@ def test_versions_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -390,7 +372,7 @@ def test_versions_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -417,7 +399,7 @@ def test_versions_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -444,7 +426,7 @@ def test_versions_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1813,6 +1795,214 @@ async def test_load_version_flattened_error_async(): ) +def test_compare_versions( + transport: str = "grpc", request_type=version.CompareVersionsRequest +): + client = VersionsClient( + 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.compare_versions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = version.CompareVersionsResponse( + base_version_content_json="base_version_content_json_value", + target_version_content_json="target_version_content_json_value", + ) + response = client.compare_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.CompareVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.CompareVersionsResponse) + assert response.base_version_content_json == "base_version_content_json_value" + assert response.target_version_content_json == "target_version_content_json_value" + + +def test_compare_versions_from_dict(): + test_compare_versions(request_type=dict) + + +def test_compare_versions_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 = VersionsClient( + 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.compare_versions), "__call__") as call: + client.compare_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.CompareVersionsRequest() + + +@pytest.mark.asyncio +async def test_compare_versions_async( + transport: str = "grpc_asyncio", request_type=version.CompareVersionsRequest +): + client = VersionsAsyncClient( + 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.compare_versions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + version.CompareVersionsResponse( + base_version_content_json="base_version_content_json_value", + target_version_content_json="target_version_content_json_value", + ) + ) + response = await client.compare_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.CompareVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.CompareVersionsResponse) + assert response.base_version_content_json == "base_version_content_json_value" + assert response.target_version_content_json == "target_version_content_json_value" + + +@pytest.mark.asyncio +async def test_compare_versions_async_from_dict(): + await test_compare_versions_async(request_type=dict) + + +def test_compare_versions_field_headers(): + client = VersionsClient(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 = version.CompareVersionsRequest() + + request.base_version = "base_version/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.compare_versions), "__call__") as call: + call.return_value = version.CompareVersionsResponse() + client.compare_versions(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", "base_version=base_version/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_compare_versions_field_headers_async(): + client = VersionsAsyncClient(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 = version.CompareVersionsRequest() + + request.base_version = "base_version/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.compare_versions), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + version.CompareVersionsResponse() + ) + await client.compare_versions(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", "base_version=base_version/value",) in kw[ + "metadata" + ] + + +def test_compare_versions_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.compare_versions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = version.CompareVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.compare_versions(base_version="base_version_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].base_version == "base_version_value" + + +def test_compare_versions_flattened_error(): + client = VersionsClient(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.compare_versions( + version.CompareVersionsRequest(), base_version="base_version_value", + ) + + +@pytest.mark.asyncio +async def test_compare_versions_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.compare_versions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = version.CompareVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + version.CompareVersionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.compare_versions(base_version="base_version_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].base_version == "base_version_value" + + +@pytest.mark.asyncio +async def test_compare_versions_flattened_error_async(): + client = VersionsAsyncClient(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.compare_versions( + version.CompareVersionsRequest(), base_version="base_version_value", + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.VersionsGrpcTransport( @@ -1913,6 +2103,7 @@ def test_versions_base_transport(): "update_version", "delete_version", "load_version", + "compare_versions", ) for method in methods: with pytest.raises(NotImplementedError): @@ -1927,7 +2118,6 @@ def test_versions_base_transport(): transport.operations_client -@requires_google_auth_gte_1_25_0 def test_versions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1951,29 +2141,6 @@ def test_versions_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_versions_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.versions.transports.VersionsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VersionsTransport( - 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_versions_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( @@ -1985,7 +2152,6 @@ def test_versions_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_versions_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -2001,26 +2167,10 @@ def test_versions_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_versions_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) - VersionsClient() - 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.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_versions_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2037,26 +2187,6 @@ def test_versions_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_versions_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", [ diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py index ca6e18f9..dc1fb474 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -36,9 +35,6 @@ from google.cloud.dialogflowcx_v3beta1.services.webhooks import WebhooksClient from google.cloud.dialogflowcx_v3beta1.services.webhooks import pagers from google.cloud.dialogflowcx_v3beta1.services.webhooks import transports -from google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.dialogflowcx_v3beta1.types import webhook from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook from google.oauth2 import service_account @@ -47,20 +43,6 @@ 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" @@ -200,7 +182,7 @@ def test_webhooks_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -217,7 +199,7 @@ def test_webhooks_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -234,7 +216,7 @@ def test_webhooks_client_client_options(client_class, transport_class, transport 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() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -263,7 +245,7 @@ def test_webhooks_client_client_options(client_class, transport_class, transport 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -320,7 +302,7 @@ def test_webhooks_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -362,7 +344,7 @@ def test_webhooks_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -384,7 +366,7 @@ def test_webhooks_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -411,7 +393,7 @@ def test_webhooks_client_client_options_scopes( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -438,7 +420,7 @@ def test_webhooks_client_client_options_credentials_file( 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) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1726,7 +1708,6 @@ def test_webhooks_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_webhooks_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1750,29 +1731,6 @@ def test_webhooks_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_webhooks_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.webhooks.transports.WebhooksTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebhooksTransport( - 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_webhooks_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( @@ -1784,7 +1742,6 @@ def test_webhooks_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_webhooks_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1800,26 +1757,10 @@ def test_webhooks_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_webhooks_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) - WebhooksClient() - 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.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport,], ) -@requires_google_auth_gte_1_25_0 def test_webhooks_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1836,26 +1777,6 @@ def test_webhooks_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [transports.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_webhooks_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", [